您的位置:首页 > 其它

LeetCode String to Integer (atoi)

2016-01-18 16:33 429 查看
原题链接在这里:https://leetcode.com/problems/string-to-integer-atoi/

先把前后的空格去掉,然后取首个符号位。

注意溢出,若是res已经大于Intger.MAX_VALUE/10, res*10就会溢出,若是res == Integer.MAX_VALUE/10, 但最后一位比8大都会溢出,因为Integer的范围是 -2147483648 到 2147483647, 最后一位若是8的话就会溢出Integer.MAX_VALUE 的最后一位7.

Time Complexity: O(str.length()). Space: O(1).

AC Java:

public class Solution {
public int myAtoi(String str) {
if(str == null || str.length() == 0){
return 0;
}

//去掉前后空格
str = str.trim();
int i = 0;
char flag = '+';
//首个char是符号
if(str.charAt(i) == '+'){
i++;
}else if(str.charAt(i) == '-'){
flag = '-';
i++;
}

int res = 0;
while(i<str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9'){
//溢出
if(res > Integer.MAX_VALUE/10 || (res == Integer.MAX_VALUE/10 && str.charAt(i)>='8')){
return flag == '+' ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
res = res*10 + (str.charAt(i)-'0');
i++;
}
if(flag == '-'){
res = -res;
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: