Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
Update (2015-02-10):
The signature of the C++
function had been updated. If you still see your function signature accepts a const char *
argument, please click the reload button to reset your code definition.
spoilers alert... click to show requirements for atoi.
Subscribe to see which companies asked this question
String to Integer (atoi)思路:注意题目要求,有以下几点
1.大于Integer.MAX_VALUE的返回Integer.MAX_VALUE
2.小于Integer.MIN_VALUE的返回Integer.MIN_VALUE
3.符号出现2次返回0
4.出现过数字后再出现非数字的如空格或者英文直接返回前面读取到的数字
GitHub地址:https://github.com/corpsepiges/leetcode
public class Solution {
public int myAtoi(String str) {
char[] cs=str.toCharArray();
long ans=0;
int sign=1;
boolean signFlag=true;
int i=0;
boolean zeroFlag=true;
while (i < cs.length) {
if (zeroFlag) {
while (cs[i]==' ') {
i++;
}
zeroFlag=false;
}
if (!zeroFlag&&cs[i]==' ') {
break;
}
if (cs[i]=='-'||cs[i]=='+') {
if (signFlag) {
sign=44-cs[i];
signFlag=false;
}else{
return 0;
}
}else if(cs[i]>='0'&&cs[i]<='9'){
ans=10*ans+cs[i]-48;
if (sign==1&&ans>=Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
if (sign==-1&&ans-1>=Integer.MAX_VALUE) {
return Integer.MIN_VALUE;
}
}else{
break;
}
i++;
}
return (int) (ans*sign);
}
}