Tuesday, September 10, 2013

String to integer@leetcode

刷题必备书籍Cracking the Coding Interview: 150 Programming Questions and Solutions 

简历:The Google Resume: How to Prepare for a Career and Land a Job at Apple, Microsoft, Google, or any Top Tech Company
算法学习书籍:Introduction to Algorithms
编程珠玑:Programming Pearls (2nd Edition)
C++ 学习:The C++ Programming Language, 4th Edition
经典操作系统书籍,龙书:Operating System Concepts
创业:The Start-up of You: Adapt to the Future, Invest in Yourself, and Transform Your Career
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
» Solve this problem

这道题我困惑了一下,看了答案还是困惑了一下。后来洗澡那会儿想明白了他是怎么处理是否溢出的情况了,而且res=res*10+str[i]-'0'一定要写在后面,因为若已经超过了再去判断,就不对了,那个时候res已经不是我们需要去比较的值了。

然后INT_MAX除以10去判断,是因为下一轮res就要乘以10,在等res没有超出范围时就判断,才对!下面一个是我的代码。


class Solution {
public:
int atoi(const char *str) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int res=0;
bool s=true;
int m=0;
while(str[m]==' ')
m++;
if(str[m]=='+'||str[m]=='-')
{
if(str[m]=='-')
s=false;
m++;
}
for(int i=m; i<strlen(str); i++)
{
if(str[i]<'0'||str[i]>'9')
break;
if(INT_MAX/10<res||INT_MAX/10==res&&INT_MAX%10<str[i]-'0')
{
return s==false? INT_MIN : INT_MAX;
}
res=res*10+str[i]-'0';
}
return s==false? -res : res;
}
};
class Solution {
public:
int atoi(const char *str) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
while(*str==' ')
{
str++;
}
bool res;
if(*str=='-'||*str=='+')
{
res = (*str=='-')? false : true;
str++;
}
int sum = 0;
while(*str>='0'&&*str<='9')
{
if(sum>INT_MAX/10&&(*str>='0'&&*str<='9')) return res==true? INT_MAX : INT_MIN;
else if(sum==INT_MAX/10&&(*str>='0'&&*str<='9'))
{
if(*str>='7'&&res==true)
return INT_MAX;
else if(*str>='8'&&res==false)
return INT_MIN;
return res==true? (sum*10+*str-'0') : -(sum*10 + *str-'0');
}
sum = sum*10 + *str-'0';
str++;
}
return res==true? sum : -sum;
}
};

1 comment:

Leetcode 316. Remove Duplicate Letters

 这道题表面问的是如何删除重复,实际在问如何从多个字符选取一个保留,从而让整个字符串按升序排列。那么策略就是对于高顺位的字符比如‘a',就要选靠前位置的保留,而低顺位字符如’z'则应该尽量选取靠后位置保留。 算法大概思路:每看到一个字符,我们要决定是否保留 1. ...