[LeetCode] 8. String to Integer (atoi)

Implement atoi to convert a string to an integer.

 public class Solution {
public int myAtoi(String s) {
if (s == null || s.length() < 1) {
return 0;
}
int i = 0;
while (i < s.length() && s.charAt(i) == ' ') {
i++;
}
if (i == s.length()) {
return 0;
}
boolean isN = false;
if (s.charAt(i) == '-') {
isN = true;
i++;
} else if (s.charAt(i) == '+') {
i++;
}
double r = 0;
for (; i < s.length(); i++) {
if (s.charAt(i) < '0' || s.charAt(i) > '9') {
break;
}
r = r * 10 + (s.charAt(i) - '0');
}
if (isN) {
r = -r;
if (r < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
} else if (r > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
return (int)r;
}
}
上一篇:Java开发11个过不去的梗


下一篇:PhoneGap+Xcode6环境配置