My simple solution


  • 218
    Y

    I think we only need to handle four cases:

    1. discards all leading whitespaces
    2. sign of the number
    3. overflow
    4. invalid input

    Is there any better solution? Thanks for pointing out!

    int atoi(const char *str) {
        int sign = 1, base = 0, i = 0;
        while (str[i] == ' ') { i++; }
        if (str[i] == '-' || str[i] == '+') {
            sign = 1 - 2 * (str[i++] == '-'); 
        }
        while (str[i] >= '0' && str[i] <= '9') {
            if (base >  INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > 7)) {
                if (sign == 1) return INT_MAX;
                else return INT_MIN;
            }
            base  = 10 * base + (str[i++] - '0');
        }
        return base * sign;
    }

  • 29
    A

    This code handle -2147483648 as overflow, but it is not.


  • 17
    L

    It is not overflow, but the above code will still return correctly for this case. it will return INT_MIN.


  • 1
    E

    Very concise and elegant code! I think your solution is the best one. And the way you handled the overflow case is very smart!


  • 1
    K

    Overflow is handled well. But why is it always going to be 7?


  • 3
    Y

    Because INT_MAX has been divided by 10, so the tail vanishes. if the tail is 8 or 9, it will overflow.


  • 0
    X

    very smart!!!!!!!!!!!!!


  • 0
    M

    elegant!!! Like it !!!


  • 0
    W

    very nice code. But why 8 or 9 will cause overflow?


  • 0
    A

    Really concise!


  • 0
    S

    brief and smart


  • 15
    M

    I don't like the magic number '7' , it's better to substitute it to INT_MAX%10


  • 0
    H

    My code with similar idea, using substring. Thanks for sharing!

        public class Solution {
    public int myAtoi(String str) {
    	int result = 0, i = 0, sign = 1;
    	if(str == null || str.length() == 0)
    	    return result;
        char[] arr = str.toCharArray();
        while(arr[i]==' ' && i< arr.length)
    		i++;
    	if(i==arr.length)
    		return result;
    	if(arr[i] == '-' || arr[i] == '+'){
    		sign = arr[i] == '-'? -1: 1;
    		i++;
    	}
    	int j = i;
    	for(; j < str.length(); j++){
    		if(arr[j] >'9' || arr[j] <'0')
    			break;
    		if((j > i) && 
    		    (Integer.parseInt(str.substring(i, j)) > Integer.MAX_VALUE/10 ||
    		    (Integer.parseInt(str.substring(i, j)) == Integer.MAX_VALUE/10 &&
    		      (sign == 1 && arr[j]>='7' || sign == -1&& arr[j] >= '8'))))
    		    return sign == 1? Integer.MAX_VALUE: Integer.MIN_VALUE;
    	}
    	result = i==j? 0: Integer.parseInt(str.substring(i, j));
    	return result*sign;
    }
    

    }


  • 25

    Very concise code, thanks! Rewrite your code with Java.

    public static int myAtoi(String str) {
        if (str.isEmpty()) return 0;
        int sign = 1, base = 0, i = 0;
        while (str.charAt(i) == ' ')
            i++;
        if (str.charAt(i) == '-' || str.charAt(i) == '+')
            sign = str.charAt(i++) == '-' ? -1 : 1;
        while (i < str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
            if (base > Integer.MAX_VALUE / 10 || (base == Integer.MAX_VALUE / 10 && str.charAt(i) - '0' > 7)) {
                return (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }
            base = 10 * base + (str.charAt(i++) - '0');
        }
        return base * sign;
    }

  • 0
    S

    Thanks for sharing, my code in python.

    class Solution:
    # @param {string} str
    # @return {integer}
    def myAtoi(self, str):
        res = 0
        n = len(str)
        i = 0
        if i >=n:
            return 0
        while(i < n and str[i] == ' '):
            i += 1
        sig = 1
        if str[i] == '-' or str[i] == '+':
            sig = 1 - 2 * (str[i] == '-')
            i += 1
        
        while(i < n and ord(str[i])>=ord('0') and ord(str[i])<=ord('9')):
            int_v = int(str[i])
            if (res > 214748364 or (res == 214748364 and int_v>7)):
                if sig == 1:
                    return 2147483647
                else:
                    return -2147483648
            res = res * 10 + int_v
            i += 1
        return res * sig

  • 0
    C

    There is one function could test add overflow

    int testAddOverflow(int a,int b){
        int sum = a + b;
        return a > sum;
    }
    

    here is my AC version

    int testAddOverflow(int a,int b){
        int sum = a + b;
        return a > sum;
    }
    int myAtoi(char* str) {
        int val = 0;
        int sig = 1;
    
        while(*str == ' '){
            str++;
        }
        if(*str == '+'){
            str ++;
        }else if(*str == '-'){
            sig = -1;
            str ++;
        }
        if(*str < '0' || *str > '9'){
            return 0;
        }
        while(*str >= '0' && *str <= '9'){
            if(val > 0x7fffffff / 10 || testAddOverflow(val * 10, *str - '0')){
                if(1 == sig){
                    return 0x7fffffff;
                }else{
                    return 0x80000000;
                }
            }
            val = 10 * val + *str - '0';
            str ++;
        }
    
        return val * sig;
    }
    

  • 0
    Y

    aaaaaawesome!!!


  • 0
    C

    if the machine is 5 bits, so the range of int will be -16 to 15. when base=1, tail=6, it could cause overflow. but it is not detected. sorry for my bad english!!


  • 0
    F

    it will be a bit easier if define base as long and return when base overflow.


  • 0
    M

    for this code -2147483648 is overflow, for overflow it will return -2147483648, that is itself.


Log in to reply
 

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