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.
代码如下:
public static int reverse(String str) {
String s = str.trim();
int length = s.length();
if(length == 0){
return 0;
}
boolean isPositive = true;
int i = 0;
if(s.charAt(i)=='-'||s.charAt(0)=='+'){
if(s.charAt(0)=='-'){
isPositive = false;
i++;
}else {
while(s.charAt(++i)=='+'){
}
if(s.charAt(i)=='-'){
isPositive = false;
i++;
}
}
}
long revResult = 0;
while(i < length){
if(s.charAt(i)!= ' '){
revResult = revResult*10 + s.charAt(i)-'0';
}
i++;
}
if(isPositive == false){
revResult = -revResult;
}
return (int)revResult;
}