Can't We Use BigInteger for This Question?


  • 0
    H

    public class Solution {
    public static int myAtoi(String str) {

    	int len = str.length();
    
    	// empty string
    	if (len == 0)
    		return 0;
    
    	// remove prefix spaces
    	int i;
    	for (i = 0; i < len; i++) {
    		if (str.charAt(i) != ' ')
    			break;
    	}
    	str = str.substring(i);
    
    	// initial plus or minus sign
    	if (str.charAt(0) == '+' || str.charAt(0) == '-') {
    		i = 1;
    	} else {
    		i = 0;
    	}
    	// recognize the integer part
    	len = str.length();
    	int j;
    	for (j = i; j < len; j++) {
    		char s = str.charAt(j);
    		if (s < '0' || s > '9')
    			break;
    	}
    	if (i==j) return 0; // only initial plus or minus sign
    	str = str.substring(0, i);
    	// no valid conversion
    	if (str.length() == 0)
    		return 0;
    
    	// check bounds
    	BigInteger max = new BigInteger(String.valueOf(Integer.MAX_VALUE));
    	BigInteger min = new BigInteger(String.valueOf(Integer.MIN_VALUE));
    	BigInteger myBigInteger = new BigInteger(str);
    	if (myBigInteger.compareTo(max) == 1)
    		return Integer.MAX_VALUE;
    	if (myBigInteger.compareTo(min) == -1)
    		return Integer.MIN_VALUE;
    
    	return Integer.valueOf(str);
    }
    

    }


Log in to reply
 

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