We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent bbb63be commit e251f9eCopy full SHA for e251f9e
lcof/面试题67. 把字符串转换成整数/Solution.cpp
@@ -0,0 +1,35 @@
1
+class Solution {
2
+public:
3
+ int StrToInt(string str) {
4
+ int res = 0, bndry = INT_MAX / 10;
5
+ int i = 0, sign = 1, length = str.size();
6
+ if(length == 0) {
7
+ return 0;
8
+ }
9
+ // 删除首部空格
10
+ while(str[i] == ' '){
11
+ if(++i == length) {
12
13
14
15
+ //若有负号则标识符号位
16
+ if(str[i] == '-') {
17
+ sign = -1;
18
19
+ if(str[i] == '-' || str[i] == '+') {
20
+ i++;
21
22
+ for(int j = i; j < length; j++) {
23
+ if(str[j] < '0' || str[j] > '9') {
24
+ break;
25
26
+ //res>214748364越界;res=214748364且str[j] > '7'越界
27
+ if(res > bndry || res == bndry && str[j] > '7'){
28
+ return sign == 1 ? INT_MAX : INT_MIN;
29
30
+ //从左向右遍历数字并更新结果
31
+ res = res * 10 + (str[j] - '0');
32
33
+ return sign * res;
34
35
+};
0 commit comments