Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4b72ddb

Browse files
feat: add cpp solution to lcof problem: No.67 (#3790)
1 parent e385a55 commit 4b72ddb

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed

‎lcof/面试题67. 把字符串转换成整数/README.md‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,46 @@ class Solution {
143143
}
144144
```
145145

146+
#### C++
147+
148+
```cpp
149+
class Solution {
150+
public:
151+
int strToInt(string str) {
152+
int res = 0, bndry = INT_MAX / 10;
153+
int i = 0, sign = 1, length = str.size();
154+
if (length == 0) {
155+
return 0;
156+
}
157+
// 删除首部空格
158+
while (str[i] == ' ') {
159+
if (++i == length) {
160+
return 0;
161+
}
162+
}
163+
// 若有负号则标识符号位
164+
if (str[i] == '-') {
165+
sign = -1;
166+
}
167+
if (str[i] == '-' || str[i] == '+') {
168+
i++;
169+
}
170+
for (int j = i; j < length; j++) {
171+
if (str[j] < '0' || str[j] > '9') {
172+
break;
173+
}
174+
// res>214748364越界;res=214748364且str[j] > '7'越界
175+
if (res > bndry || res == bndry && str[j] > '7') {
176+
return sign == 1 ? INT_MAX : INT_MIN;
177+
}
178+
// 从左向右遍历数字并更新结果
179+
res = res * 10 + (str[j] - '0');
180+
}
181+
return sign * res;
182+
}
183+
};
184+
```
185+
146186
#### Go
147187
148188
```go
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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+
return 0;
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /