题目
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.
spoilers alert... click to show requirements for atoi.
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
注意各种边界情况。
代码
public class StringToInteger { public int atoi(String str) { if (str == null || str.length() == 0) { return 0; } // trim int N = str.length(); int start = 0; while (start < N && str.charAt(start) == ‘ ‘) { ++start; } if (start == N) { return 0; } // get sign boolean isNeg = false; if (str.charAt(start) == ‘-‘) { isNeg = true; ++start; } else if (str.charAt(start) == ‘+‘) { ++start; } // calc long result = 0; for (int i = start; i < N; ++i) { if (str.charAt(i) >= ‘0‘ && str.charAt(i) <= ‘9‘) { result = result * 10 + str.charAt(i) - ‘0‘; if (result > Integer.MAX_VALUE) { return isNeg ? Integer.MIN_VALUE : Integer.MAX_VALUE; } } else { break; } } return isNeg ? -(int) result : (int) result; } }
LeetCode | String to Integer (atoi),布布扣,bubuko.com
LeetCode | String to Integer (atoi)
原文:http://blog.csdn.net/perfect8886/article/details/23282901