Description
Implement atoi
to convert a string to an integer.
解:
此题需要注意的问题:
- 字符串中可能有空格
- 开头可能有正负号,且只能有一个符号,多于一个时为错误串
- 需要判断结果是否越界
java代码:
class Solution {
public int myAtoi(String str) {
if (str == null || str.length() < 1)
return 0;
// 消除空格
str = str.trim();
// 记录正负
boolean flag = true;
int i = 0;
if (str.charAt(0) == '-'){
flag = false;
i++;
}else if(str.charAt(0) == '+'){
i++;
}
double res = 0;
for (; i < str.length() && str.charAt(i) <= '9' && str.charAt(i) >= '0'; i++){
res = res * 10 + (str.charAt(i) - '0');
}
if (!flag)
res = -res;
if (res > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
if (res < Integer.MIN_VALUE)
return Integer.MIN_VALUE;
return (int)res;
}
}