8. String to Integer (atoi)

来源:互联网 发布:手机音乐可视化软件 编辑:程序博客网 时间:2024/05/29 19:24
public class Solution {    public int myAtoi(String str) {        Boolean negativeFlag = false;        Boolean positiveFlag = false;        int st = 0;        long ans = 0;        long max = 2147483648L;        if(str.equals("")){            return 0;        }        while(st < str.length() && str.charAt(st) == ' '){            st ++;        }        if(st < str.length() && str.charAt(st) == '+') {            st++;            positiveFlag = true;        }else{            if(st < str.length() && str.charAt(st) == '-'){                st ++;                negativeFlag = true;            }           }        if(negativeFlag == true && positiveFlag == true){            return 0;         }else{                        for(int i = st;i < str.length(); i++){                if(str.charAt(i) <= '9' && str.charAt(i) >= '0'){                    ans = ans * 10 + str.charAt(i) - '0';                       if(ans > max){                        ans = (int)max;                        if(negativeFlag)                            return  Integer.MIN_VALUE;                        if(positiveFlag || (negativeFlag ==false && positiveFlag == false))                            return  Integer.MAX_VALUE;                        break;                    }                                       }                 else                     break;            }        }        if(negativeFlag)  ans = -ans;        if(ans >= Integer.MAX_VALUE)   ans = Integer.MAX_VALUE;          if(ans <= Integer.MIN_VALUE)   ans = Integer.MIN_VALUE;                                   return (int)ans;            }}

注意考虑 + - 空格 无效字符  除正负号外,大于2147483647的数,比如“-2147483648”,除符号“-”外,“2147483648”是大于int的最大值2147483647的,故返回应该是 -2147483648