leetcode 8 String to Integer

1315 ワード

Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
正数で判断しても大丈夫:ret>(Integer.MAX_VALUE-(c-'0')/dw)
負数の場合は正数で演算する、ret>(Integer.MAX_VALUE-(c-'0')/dw)を超えてIntegerに設定.MIN_VALUE;
public class Solution {
    public int myAtoi(String str) {
        if(str==null || str.length()==0)
            return 0;
        str=str.trim();
        int ret=0;
        boolean isPosi=true;
        for(int i=0;i='0' && str.charAt(i)<='9'){
                char c=str.charAt(i);
                if(ret>(Integer.MAX_VALUE-(c-'0'))/10){
                    return isPosi? Integer.MAX_VALUE : Integer.MIN_VALUE;
                }
                ret*=10;
                ret += c - '0';
            }
            else{
                return isPosi?ret:-ret;
            }
        }
        return isPosi?ret:-ret;
    }
}