File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff 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
You can’t perform that action at this time.
0 commit comments