String to Integer

Source

Implement function atoi to convert a string to an integer.

If no valid conversion could be performed, a zero value is returned.

If the correct value is out of the range of representable
values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

Example
"10" => 10
"-1" => -1
"123123123123123" => 2147483647
"1.0" => 1

Java

public class Solution {
    /**
     * @param str: A string
     * @return An integer
     */
    public int atoi(String str) {
        long result=0;
        int sign=1;

        int index=0;
        while(index<str.length() && str.charAt(index)==' '){
            index++;
        }
        if(index==str.length()){
            return (int)result;
        }

        if(str.charAt(index)=='+'){
            index++;
        }
        else if(str.charAt(index)=='-'){
            sign=-1;
            index++;
        }

        while(index<str.length()){
            if(Character.isDigit(str.charAt(index))==false){
                break;
            }
            result = result*10+str.charAt(index)-'0';
            if(sign>0 && result>Integer.MAX_VALUE){
                return Integer.MAX_VALUE;
            }
            if(sign<0 && -result<Integer.MIN_VALUE){
                return Integer.MIN_VALUE;
            }
            index++;
        }
        return (int)result*sign;
    }
}

Python

class Solution:
    # @param str: a string
    # @return an integer
    def atoi(self, str):
        result=0
        sign=1

        index=0
        while index<len(str) and str[index]==' ':
            index+=1

        if index==len(str):
            return result

        if str[index]=='+':
            sign=1
            index+=1
        elif str[index]=='-':
            sign=-1
            index+=1

        while index<len(str):
            if str[index].isdigit()==False:
                break
            result = result*10 + int(str[index])

            if sign==1 and sign*result>2**31-1:
                return 2**31-1
            if sign==-1 and sign*result<-2**31:
                return -2**31
            index+=1   
        return sign*result