Leetcode–Valid Number

The Problem:

Validate if a given string is numeric.

Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true

Notes:

  1. The problem is ambigous and need to clarify a lot of special cases before implementing. Some cases I found in test cases that are not that intuitive are:
    1. 01 ->true
      e9->false
      3. ->true
      .1 -> true
      46.e3-> true
  2. Notice that for ‘e’ and ‘.’ can only appear once. And all special non-digit characters has rules for the character following. When using flag to mark its immediate follower, need to reset all the flags in all the branches.

Java Solution

public class Solution {

    public boolean isNumber(String s) {
        s = s.trim();
        if(s.length()==0) return false;
        boolean foloDot = false;
        boolean hasExpo = false;
        boolean foloE = false;
        boolean hasDot = false;
        boolean hasSign = false;
        boolean foloSign = false;
        boolean hasNum = false;
        for(int i = 0; i < s.length(); i++){
            char ch = s.charAt(i);
            if(ch=='e'){
                if(!hasNum ||hasExpo || foloSign ||  i==s.length()-1)
                    return false;
                hasExpo = true;
                foloE = true;
                foloDot = false;
                foloSign = false;
            }
            else if(ch=='.'){
                if((!hasNum&&i==s.length()-1)  || hasDot || hasExpo )
                    return false;
                hasDot = true;
                foloDot = true;
                foloE = false;
                foloSign = false;
            }
            else if(ch=='+' || ch=='-'){
                if((hasSign && !foloE)|| i==s.length()-1 || (hasNum && !foloE) || foloDot)
                    return false;
                hasSign = true;
                foloSign = true;
                foloDot = false;
                foloE = false;
            }
            else if(ch>='0' && ch <='9'){
                foloDot = false;
                foloE = false;
                foloSign = false;
                hasNum = true;
            }
            else
                return false;
        }
        return true;
    }
}

Leetcode–String to Integer (atoi)

The Problem:

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.

Requirements for atoi:The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

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.

Notes:

  1. The key to solve a problem like this is :
    1. clarify the problem, consider how the function would behave for all corner cases. 2. pay attention to details.
  2. One thing to mention for all the conversion to integer: be careful about the range.
    1. Fact: INT_MAX (2147483647) !=  – INT_MIN (-2147483648)

Java Solution

public class Solution {
    public int atoi(String str) {
        int result = 0;
        str =str.trim();
        if(str.length()==0)
            return result;
        boolean neg = false;
        boolean nxtN = false;
        for(int i = 0; i < str.length(); i++){
            if(result==0 && str.charAt(i)=='-'){
                if(nxtN)return 0;
                neg = true;
                nxtN = true;
            }
            else if(result ==0 && str.charAt(i)=='+' ){
                if(nxtN)return 0;
                neg = false;
                nxtN = true;
            }
            //breaks a valid number
            else if(!(str.charAt(i)>='0' && str.charAt(i)<='9')){
                break;
            }
            else if(str.charAt(i)>='0' && str.charAt(i)<='9'){
                nxtN = true;
                int temp = str.charAt(i)-'0';
                // check the integer bound
                // note the condition for temp is > not >=
                // watch out that Integer.MIN_VALUE != -Integer.MAX_VALUE 
                if((result  == (Integer.MAX_VALUE)/10 && temp > (Integer.MAX_VALUE%10))||
                (result > (Integer.MAX_VALUE)/10)){
                        return neg ? Integer.MIN_VALUE: Integer.MAX_VALUE;
                }
                else
                    result = result *10 + temp;
            }
        }
        return neg ? 0-result : result;
    }
}