3.3 String to Integer(atoi)

来源:互联网 发布:淘宝网最小手机 编辑:程序博客网 时间:2024/06/06 00:22

按照leetcode戴的C++版本对照写的java版。还需要再练习单独写。

public class Solution {    public int atoi(String str) {        if(str.length() == 0 || str == null) return 0;        int sign = 1;        int i = 0;        int num = 0;        while(str.charAt(i) == ' ' && i < str.length()){                i++;        }        if(str.charAt(i) == '+'){            i++;        }        else if (str.charAt(i) == '-'){            sign = -1;            i++;        }        for(; i < str.length(); i++){            if(str.charAt(i) <'0' || str.charAt(i) > '9') break;            else if (num > Integer.MAX_VALUE/10 || (num == Integer.MAX_VALUE/10 && (str.charAt(i) - '0' > Integer.MAX_VALUE%10))){                return sign == -1? Integer.MIN_VALUE : Integer.MAX_VALUE;            }            num = num * 10 + str.charAt(i) - '0';        }        return sign * num;    }}


我第二次写的代码:注意:

记得要考虑符号

把char 转换成int,不能用Integer.parseInt (char), 而要用char - '0' 

public class Solution {    public int atoi(String str) {        int result = 0;        if(str == null || str.length() == 0){            return result;        }        int i = 0;        while(str.charAt(i) == ' ' && i < str.length()){//ignore the preceeding spaces            i++;        }        for(;i < str.length(); i++){            char c = str.charAt(i);            if(c < '0' || c > '9') continue;            int num = Integer.parseInt(c);            result = result * 10 + num;        }        if(result > Integer.MAX_VALUE){            result = Integer.MAX_VALUE;        }        else if(result < Integer.MIN_VALUE){            result = Integer.MIN_VALUE;        }        return result;    }}


http://blog.csdn.net/linhuanmars/article/details/21145129

的解法不同于上面的:对吗?e.g. Integer.MAX_VALUE = 55, 那res = 56时,我们应该返回MAX_VALUE。但按这个程序不返回MAX_VALUE.

if(isNeg && res>-((Integer.MIN_VALUE+digit)/10))              return Integer.MIN_VALUE;  else if(!isNeg && res>(Integer.MAX_VALUE-digit)/10)              return Integer.MAX_VALUE;  



0 0
原创粉丝点击