LeetCode_8_String_to_Integer(atoi)

LeetCode_8_String_to_Integer(atoi)

问题描述

Implement atoi which converts a string to an integer.

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

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

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned.

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (2^31 − 1) or INT_MIN (−2^31) is returned.
简单的说就是把一个string转为int

样例

Alt text

代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
public:
int myAtoi(string str) {
long long re = 0;
int len = str.length();
int i, j;
i = 0;
int fu = 1;
//排除一开始的空字符
while(str[i] == ' ') i++;
//判定符号和非法字符串
if(str[i] == '-') {
fu = -1, i++;
}
else if(str[i] == '+') {
fu = 1, i++;
}
else if(str[i] < '0' || str[i] > '9') return 0;
//cout << i << endl;
//遍历求值
for(; i < len; i++) {
//若为数字,求和,否则返回当前值
if(str[i] >= '0' && str[i] <= '9') {
re = re * 10 + str[i]-'0';
//判断边界
if(re*fu < pow(-2,31)) return pow(-2,31);
else if(re*fu > pow(2,31)-1) return pow(2,31)-1;
} else return re*fu;
}
return re*fu;
}
};