Brute force solution in java...

  • 0
    public int myAtoi(String str) {
        if(str==null||str.length()<1) return 0;
    	long result=0;
    	int a=1;
    	if(str.charAt(0)=='-') a = -1;
    	else if(str.charAt(0)=='+') a = 1;
    	else if(str.charAt(0)<'0'||str.charAt(0)>'9') return 0;
    	else result = str.charAt(0)-'0';
        for(int i=1;i<str.length()&&result>=-2147483648&&result<=2147483647;i++){
            char temp = str.charAt(i);
            if(temp<'0'||temp>'9') return (int)result*a;
            result = result*10+(temp-'0');
        if(result*a>2147483647) return 2147483647;
        if(result*a<-2147483648) return -2147483648;
        return (int)result*a;

Log in to reply

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