Comments (1)
这道题看上去挺简单的。但属于难题,通过率也不高。
但也没觉得有那么难。题目里说了几个要注意的点。
需要注意几点:
- 要注意字符串前面的空格,直接忽略。而对于已经读取到符号或者数字之后,遇到的空格,直接return 当前的结果的值。
- 正负号:只关注首次出现的正负号,其他时刻遇到正负号就当其他字符处理,return 当前结果。当还没遇到正负号就遇到数字时,就认为是已经遇到了“+”。
- 溢出:溢出有两个来源,一个是对于上一次的结果乘十,我们用乘十再除十来判断是否出现此乘法溢出。对于加减法的溢出,当正数经过加之后变负,或者负数减之后变成正,都可以认为是溢出。这里通过除以代表当前正负值的sign来判断。但对于最小的整数INT_MIN,其除以-1之后会得到INT_MAX+1,导致溢出,所以要单独判断。
int myAtoi(char *str) {
int i;
int result = 0;
int sign = 0;
for (i = 0; str[i] != '\0'; i++) {
if (str[i] == ' ') { //跳过空格
if(sign!=0){ //如果不是字符串开始时的空格,直接return
return result;
}
continue;
}
//检查符号,只在没有遇到过符号的时候关系符号,其他时候就当"其他字符"来处理
if(sign==0){
if(str[i]=='-'){
sign = -1;
continue;
}else if(str[i]=='+'){
sign = 1;
continue;
}
}
if (str[i] >= '0' && str[i] <= '9') {
//对于首个出现的数字,设置符号为+
if (result == 0 && sign == 0) {
sign = 1;
}
//判断乘10之后会不会溢出,如果回,就返回
if (result * 10 / 10 != result) {
return (sign == 1 ? INT_MAX : INT_MIN);
}
result = result * 10 + (str[i] - '0') * sign;
//判断加减是否会溢出。因为下溢和上溢都会改变符号。
//但,对于INT_MIN,就不能通过除以sign的方式来判断,所以要特别判断。
if (result==INT_MIN||result / sign < 0) {
return (sign == 1 ? INT_MAX : INT_MIN);
}
} else { //其他字符
return result;
}
}
return result;
}
from leet_code_discussion.
Related Issues (5)
- 7. Reverse Integer HOT 1
- 12. Integer to Roman HOT 1
- 13. Roman to Integer HOT 1
- 11. Container With Most Water HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from leet_code_discussion.