您的位置:首页 > 其它

Leetcode: String to Integer (atoi)

2015-09-10 21:51 387 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: