String to Integer (atoi)
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.
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 Solution {
public int myAtoi(String str) {
if (str == null) {
return 0;
}
str = str.trim();
if (str.length() == 0) {
return 0;
}
int flag = 0;
double re = 0;
if (str.charAt(0) == '-') {
flag = 1;
}
else if (str.charAt(0) == '+') {
}
else if ((str.charAt(0) >= '0' && str.charAt(0) <= '9')) {
re = 10*re + (str.charAt(0)-'0');
}
else {
return 0;
}
for (int i = 1;i < str.length();i++) {
if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
re = 10*re + (str.charAt(i)-'0');
}
else {
break;
}
}
if (flag == 1) {
re = -re;
}
if (re > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
else if (re < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
else {
return (int)re;
}
}
}
本文介绍了一个将字符串转换为整数的atoi函数实现方法。文章详细解释了如何处理各种输入情况,包括忽略前导空格、解析正负号、读取数字字符直至非数字字符出现等步骤,并确保转换结果在整数范围内。
482

被折叠的 条评论
为什么被折叠?



