Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

feat: add cpp solution to lcof problem: No.67 #3790

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Nov 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions lcof/面试题67. 把字符串转换成整数/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,46 @@ class Solution {
}
```

#### C++

```cpp
class Solution {
public:
int strToInt(string str) {
int res = 0, bndry = INT_MAX / 10;
int i = 0, sign = 1, length = str.size();
if (length == 0) {
return 0;
}
// 删除首部空格
while (str[i] == ' ') {
if (++i == length) {
return 0;
}
}
// 若有负号则标识符号位
if (str[i] == '-') {
sign = -1;
}
if (str[i] == '-' || str[i] == '+') {
i++;
}
for (int j = i; j < length; j++) {
if (str[j] < '0' || str[j] > '9') {
break;
}
// res>214748364越界;res=214748364且str[j] > '7'越界
if (res > bndry || res == bndry && str[j] > '7') {
return sign == 1 ? INT_MAX : INT_MIN;
}
// 从左向右遍历数字并更新结果
res = res * 10 + (str[j] - '0');
}
return sign * res;
}
};
```

#### Go

```go
Expand Down
35 changes: 35 additions & 0 deletions lcof/面试题67. 把字符串转换成整数/Solution.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
class Solution {
public:
int strToInt(string str) {
int res = 0, bndry = INT_MAX / 10;
int i = 0, sign = 1, length = str.size();
if (length == 0) {
return 0;
}
// 删除首部空格
while (str[i] == ' ') {
if (++i == length) {
return 0;
}
}
// 若有负号则标识符号位
if (str[i] == '-') {
sign = -1;
}
if (str[i] == '-' || str[i] == '+') {
i++;
}
for (int j = i; j < length; j++) {
if (str[j] < '0' || str[j] > '9') {
break;
}
// res>214748364越界;res=214748364且str[j] > '7'越界
if (res > bndry || res == bndry && str[j] > '7') {
return sign == 1 ? INT_MAX : INT_MIN;
}
// 从左向右遍历数字并更新结果
res = res * 10 + (str[j] - '0');
}
return sign * res;
}
};
Loading