[LeetCode] String to Integer(atoi)

来源:互联网 发布:上古世纪人物捏脸数据 编辑:程序博客网 时间:2024/06/07 20:26
[Problem]

Implement atoi toconvert a string to an integer.

Hint: Carefully consider all possible input cases. If youwant a challenge, please do not see below and ask yourself what arethe possible input cases.

Notes: It is intended for this problem to be specifiedvaguely (ie, no given input specs). You are responsible to gatherall the input requirements up front.

Requirements foratoi:

The function first discards as many whitespace characters asnecessary until the first non-whitespace character is found. Then,starting from this character, takes an optional initial plus orminus sign followed by as many numerical digits as possible, andinterprets them as a numerical value.

The string can contain additional characters after those thatform the integral number, which are ignored and have no effect onthe behavior of this function.

If the first sequence of non-whitespace characters in str is nota valid integral number, or if no such sequence exists becauseeither str is empty or it contains only whitespace characters, noconversion is performed.

If no valid conversion could be performed, a zero value isreturned. If the correct value is out of the range of representablevalues, INT_MAX (2147483647) or INT_MIN (-2147483648) isreturned.


[Analysis]
需要注意以下几点:
(1)过滤前导空格
(2)过滤前导正、负号(只能有一个,出现多个则认为非法)
(3)从非法字符开始往后的所有字符全部被过滤掉
(4)整数溢出,这个是最重要的,再判断最大数溢出和最小数溢出时,需要使用字符串比较大小的方法

[Solution]

class Solution {
public:
// if str is bigger than target
bool bigger(const char *str, int start, const char *target){
int len = 0, i = start, j = 0;

// get length
while(str[i] != '\0'){
if(str[i] >= '0' && str[i] <= '9'){
len++;
i++;
}
else{
break;
}
}

// compare length
if(len < strlen(target)){
return false;
}
else if(len > strlen(target)){
return true;
}
// compare value
else{
i = start;
j = 0;
while(target[j] != '\0'){
if(str[i] - '0' > target[j] - '0'){
return true;
}
else if(str[i] - '0' < target[j] - '0'){
return false;
}
i++;
j++;
}
}
return false;
}

// atoi
int atoi(const char *str) {
// Start typing your C/C++ solution below
// DO NOT write int main() function

// result
int res = 0, i = 0;
bool mark = true;
char MAX[20] = "2147483647";
char MIN[20] = "2147483648";

// filter heading blanks
while(str[i] == ' '){
i++;
}

// filter + or -
if(str[i] == '+'){
mark = true;
i++;
}
else if(str[i] == '-'){
mark = false;
i++;
}
int start = i;

// check bound
if(mark && bigger(str, start, MAX)){
return INT_MAX;
}
if(!mark && bigger(str, start, MIN)){
return INT_MIN;
}

// convert
i = start;
while(str[i] != '\0'){
if(str[i] >= '0' && str[i] <= '9'){
res = res * 10 + (str[i] - '0');
}
else{
// format error
break;
}
i++;
}

// set mark
if(!mark){
res *= -1;
}
return res;
}
};


 说明:版权所有,转载请注明出处。Coder007的博客