题目
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.
思路
这道题没什么思路,但是要主要一定要在溢出之前解决溢出!不同的编译器对溢出的处理方法不一样的,所以得到的溢出结果也是不同的,比如int的正整数溢出就是负整数什么的就肯定不对。我的想法是用unsigned int把可能溢出的情况兜住判断,可能溢出的情况无非两个,乘以10的时候,加一个个位数的时候。
代码
class Solution {
public:
bool willOverflow(unsigned int currNum, char i, bool negFlag){
const unsigned int M_INTM = INT_MAX / 10;
if(currNum > M_INTM){
return true;
} else if(currNum == M_INTM){
if(!negFlag){
if(i - '0' > 7) {
return true;
}
} else{
if(i - '0' > 8){
return true;
}
}
}
return false;
}
int myAtoi(string str) {
unsigned int retVal = 0;
bool negFlag = false;
bool overflow = false;
if(str.size() < 1)
return 0;
int i=0;
while(str[i] == ' '){
i++;
}
if(str[i] == '+')
i++;
else if(str[i] == '-'){
i++;
negFlag = true;
}
int digCount = 0;
while(i < str.size() && str[i] >= '0' && str[i] <= '9'){
if(digCount < 9 || !willOverflow(retVal, str[i], negFlag)){
retVal = retVal * 10 + str[i] - '0';
} else {
//overflow!
overflow = true;
break;
}
i++;
digCount++;
}
if(!overflow){
if(negFlag)
return -retVal;
else
return retVal;
} else {
return negFlag? INT_MIN: INT_MAX;
}
}
};