[Lintcode]String to Integer II

来源:互联网 发布:c4d r17 mac下载 编辑:程序博客网 时间:2024/06/05 09:12

Example

"10" => 10"-1" => -1"123123123123123" => 2147483647"1.0" => 1
分析:直接实现。注意空格,正负号。

public class Solution {    /**     * @param str: A string     * @return An integer     */    public int atoi(String str) {        int res = 0, start = 0;        boolean neg = false;        if(str.length() == 0) return 0;                str = str.trim();//(1)        char[] arr = str.toCharArray();        if(str.charAt(0) == '-' || str.charAt(0) == '+') {//(2)            start = 1;            neg = str.charAt(0) == '-';        }        for(int i = start; i < arr.length; i++) {            char c = str.charAt(i);            if(c == '.') {//(3)                return neg ? -res : res;            }            if(c < '0' || c > '9') return neg ? -res : res;            else {                //正最大数                if(!neg && (res * (res * 10 + c - '0') < 0))                    return Integer.MAX_VALUE;                //负最大数                else if(neg && (-res * (-res * 10 - c + '0') < 0))                    return Integer.MIN_VALUE;                else {                    res = res * 10 + c - '0';                }            }        }                return neg ? -res : res;    }}



0 0