简历: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没有超出范围时就判断,才对!下面一个是我的代码。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
}; |
写得真好
ReplyDelete