String to Integer (atoi)

来源:互联网 发布:淘宝农村事业部 编辑:程序博客网 时间:2024/04/23 22:00
    //we can set result as long    public int atoi(String str) {        // Start typing your Java solution below        // DO NOT write main() function        if(str == null || str.length() == 0) return 0;        long result = 0;        boolean flag = true;        int i = 0;        int length = str.length();        while(i < length && str.charAt(i) == ' ') i++;        if(i < length && str.charAt(i) == '+') i++;        if(i < length && str.charAt(i) == '-') {            i++;            flag = false;        }        for(; i < length; i++) {            if(str.charAt(i) == ' ' || str.charAt(i) > '9' || str.charAt(i) < '0') break;            if(result * 10 + str.charAt(i) - '0' > Integer.MAX_VALUE) {                return flag == true ? Integer.MAX_VALUE : Integer.MIN_VALUE;            }            result = result * 10 + str.charAt(i) - '0';        }        return flag == true ? (int)result : (int)(0 - result);    }    public int atoi(String str) {        // Start typing your Java solution below        // DO NOT write main() function        if(str == null || str.length() == 0) return 0;        int result = 0;        boolean flag = true;        int i = 0;        int length = str.length();        while(i < length && str.charAt(i) == ' ') i++;        if(i < length && str.charAt(i) == '+') i++;        if(i < length && str.charAt(i) == '-') {            i++;            flag = false;        }        for(; i < length; i++) {            if(str.charAt(i) == ' ' || str.charAt(i) > '9' || str.charAt(i) < '0') break;            if(result > (Integer.MAX_VALUE - (str.charAt(i) - '0')) / 10) {//pay attention here                return flag == true ? Integer.MAX_VALUE : Integer.MIN_VALUE;            }            result = result * 10 + str.charAt(i) - '0';        }        return flag == true ? result : (0 - result);    }