Java Solution with BigInteger


  • 1
    H
    import java.math.BigInteger;
    
    public class Solution {
        public int myAtoi(String str) {
            str = str.trim();
            char[] chars = str.toCharArray();
            boolean neg = false;
            int idx = 0;
            while(idx < chars.length && (chars[idx] == ' ')) idx++;
            BigInteger res = BigInteger.ZERO;
            if(idx < chars.length && (chars[idx] == '-' || chars[idx] == '+')){
                if( chars[idx] == '-')
                    neg = true;
                idx++;
            }
            for(int i = idx ; i < chars.length && chars[i] <= '9' && chars[i] >= '0'; i++){
                res = res.multiply(BigInteger.valueOf(10));
                res = res.add(BigInteger.valueOf((int)chars[i] - (int)'0'));
            }
            if(neg) res = res.multiply(BigInteger.valueOf(-1));
            if(res.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) == 1)
                res = BigInteger.valueOf(Integer.MAX_VALUE);
            if(res.compareTo(BigInteger.valueOf(Integer.MIN_VALUE)) == -1)
                res = BigInteger.valueOf(Integer.MIN_VALUE);
            return res.intValue();
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.