原题:(频率5)
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.
题意:把字符串转化为数字,C++中的atoi函数
代码和思路
//把字符串转换为数字,1:去掉空格,判断格式是否正确 2:判断是否越界,我们知道整型数据的范围是INT_MIN(-2147482648)到INT_MAX(2147483647)
class Solution {
public static int myAtoi(String str) {
if (str == null || str.length() == 0){
return 0;
}
int sign = 1;
int start =0;
long sum = 0;
//去掉空格
str = str.trim();
//正还是负
char first = str.charAt(0);
if(first=='+'){
sign = 1;
start++;
}
else if(first == '-'){
sign = -1;
start++;
}
for (int i = start; i < str.length(); 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;
}
}