Sunday, March 20, 2016

LeetCode 刷题第一阶段 String to Integer

Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
=================================================================================
Mainly consider special cases:
1. string null or "" (length = 0)
2. contains non-digit element(s): 符号位 (sign)和数位, return the int before
3. exceed int value range (check overflow). If exceed INT_MAX we return INT_MAX, if exceed INT_MIN we return INT_MIN.
4. white space
The function we would use : Integer.parseInt(String s) , we will use it to convert the string. But we have to check all conditions to avoid assertion or exception. 
Checking the first two condition is easy, we must figure out the third one.

P.S.  convert result to "long" or double will be a faster way but normally this is not a good solution so we try to avoid it. 

Attention:
 For input ”+1“ should return "1", "+-1" should return 0.
 For input "  35ab7876" should return "35"
================================================================
Code:
public class Solution {
    public int myAtoi(String str) {
        int ret = 0;
        int index = 0;
        boolean negative = false;
       if(str != null){
          // wipe out whitespace
          str = str.trim();
          if(str.length()>0){ 
          // check sign 
          char sign = str.charAt(0);
          if(sign == '+' || sign == '-'){
              if(str.length() == 1 ) return 0;
              if(sign == '-') negative = true;
              str = str.substring(1);
          }
        //check digits
        while(index < str.length()){
            if(str.charAt(index) - '0' > 9 || str.charAt(index) - '0' < 0){
                str = str.substring(0,index);
                if(str.length() == 0 ) return 0;
            } 
            index ++;
        }
        // check overflow
        if(str.length()>10){
            if(negative) return Integer.MIN_VALUE;
            if(!negative) return Integer.MAX_VALUE;
        }else if(str.length() == 10){
            if(negative && 
                str.compareTo("2147483648")>0) return Integer.MIN_VALUE;
            if(!negative  &&
                str.compareTo(Integer.toString(Integer.MAX_VALUE))>0) return Integer.MAX_VALUE;
        }
        if(negative) {
            str = "-" + str ;
        }
        ret = Integer.parseInt(str);
    }
    }
        return ret;
    }
}
=======================================
时间复杂度  n
空间复杂度 1

No comments:

Post a Comment