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.
题目解析:
1、先丢弃字符串前面的空白字符直到扫到第一个非空白字符;然后将一个合法的数值的字符串以及其前面的一个正负号一同装换为int //trim();
2、该合法数值子字符串中或后,可能包含其他非数值的特殊字符,忽略这些子字符串(在字符串中遇到非数字字符则输出之前转换后的数字);
3、若第一个非空子字符串非法的整型数值,或根本就没有,甚至该字符串可能都是特殊字符或空字符,则不作转换返回0;
4、若没有有效地转换,则返回0,若有返回数值超出边界,则返回边界值;
代码解析:此题代码比较易懂,主要用到了一个Character.isDigit(str.charAt(i))判断字符是否是数字
public class Solution {
public int myAtoi(String str) {
if (str == null || str.length() == 0)
return 0;//
str = str.trim();
char firstChar = str.charAt(0);
int sign = 1, start = 0, len = str.length();
long sum = 0;
if (firstChar == '+') {
sign = 1;
start++;
} else if (firstChar == '-') {
sign = -1;
start++;
}
for (int i = start; i < len; i++) {
if (!Character.isDigit(str.charAt(i)))
return (int) sum * sign;
sum = sum * 10 + str.charAt(i) - '0';
if (sign == 1 && sum > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
if (sign == -1 && (-1) * sum < Integer.MIN_VALUE)
return Integer.MIN_VALUE;
}
return (int) sum * sign;
}
}