String to Integer (atoi)
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.
Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your
function signature accepts a const char * argument, please click the reload
button to reset your code definition.
解题思路:
本身没有什么难度,需要弄清楚题意。比如,输入的字符一定是正确的整数格式吗?会不会溢出,若溢出如何处理?若有数字字符其他的字符如何处理?在面试中,可以向面试官问清楚这些,便可以动手写代码哒。我们可以先用一个long long类型来存储中间结果。
class Solution {
public:
int myAtoi(string str) {
int len = str.length();
if(len==0){
return 0;
}
int sign=1;
int startIndex=0;
while(str[startIndex]==' '){
startIndex++;
}
if(str[startIndex]=='-'){
startIndex++;
sign=-1;
}else if(str[startIndex]=='+'){
startIndex++;
sign=1;
}
long long tempResult=0;
for(int i=startIndex; i<len; i++){
if(str[i]<'0'||str[i]>'9'){
break;
}
tempResult *= 10;
tempResult += str[i]-'0';
if(tempResult>2147483647){
break;
}
}
tempResult *= sign;
int result = (int)tempResult;
if(result!=tempResult){
if(sign<0){
result=-2147483648;
}else{
result=2147483647;
}
}
return result;
}
};[LeetCode] String to Integer (atoi)
原文地址:http://blog.csdn.net/kangrydotnet/article/details/45096775