您的位置:首页 > 其它

LeetCode : atoi My solution

2014-10-14 16:29 363 查看
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.

public class Solution {
public int atoi(String str) {
if (str == null || str.length() == 0) {
return 0;
}
str = str.trim();
if (str.length() == 0) {
return 0;
}
long result = 0;
int negative = 1;
int Max = Integer.MAX_VALUE;
int Min = Integer.MIN_VALUE;
int index = 0;
if (str.charAt(index) == '+') {
index++;
} else if (str.charAt(index) == '-') {
negative = -1;
index++;
}
for (; index < str.length(); index++) {
char thisBit = str.charAt(index);
if (thisBit > '9' || thisBit < '0') {
break;
} else {
result = result * 10 + (thisBit - '0');
if (result > Max && negative == 1){
break;
}
}

}
result = result * negative;
if (result > Max) {
return Max;
}
if (result < Min) {
return Min;
}
return (int) result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: