题目

8. 字符串转换整数 (atoi)

答案

方法一:巧用字符串流

1
2
3
4
5
6
7
8
9
class Solution {
public:
int myAtoi(string s) {
stringstream str(s);
int n=0;
str>>n;
return n;
}
};

方法二:指针遍历

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
class Solution {
public:
int myAtoi(string s) {
int i = 0, n = s.size(), sign = 1;
long result = 0;

//跳过前导空格
while (i < n && s[i] == ' ') {
i++;
}

//处理可选符号
if (i < n && (s[i] == '+' || s[i] == '-')) {
sign = (s[i] == '-') ? -1 : 1;
i++;
}

//转换数字字符为整数
while (i < n && isdigit(s[i])) {
result = result * 10 + (s[i] - '0');
if (result * sign >= INT_MAX) {
return INT_MAX;
} else if (result * sign <= INT_MIN) {
return INT_MIN;
}
i++;
}

return result * sign;
}
};

__END__