A Short C# 148ms Solution with 3-Step Explanations


  • 0
    L
    public bool IsNumber(string s){
        //1. Pre-Process string to remove spaces, signs
        s = s.Trim().ToLower();
        if (s.Length == 0) return false;
        if (s[0] == '+' || s[0] == '-') s = s.Length == 1 ? string.Empty : s.Substring(1);
        if (s.Length == 0) return false;
    
        //2. Split string by "e" and ".", and Validate Exponent number
        string[] nums = s.Split('e'), radix = nums[0].Split('.');
        if(nums.Length > 2 || radix.Length > 2) return false;
        if (nums.Length == 2 && (nums[0].Length == 0 || !IsInteger(nums[1], true))) return false;
    
        //3. Validate Radix float number.
        if (radix.Length == 2){
            if (radix[0].Length + radix[1].Length == 0) return false;
            if (radix[0].Length > 0 && !IsInteger(radix[0], false)) return false;
            if (radix[1].Length > 0 && !IsInteger(radix[1], false)) return false;
            return true;
        } else return IsInteger(nums[0], false); //Validate Integer if Radix is an Integer
    }
    //An Integer Validator with allowSign switch to disallow/allow "+/-" in the string
    private static bool IsInteger(string s, bool allowSign){
        if (s.Length == 0) return false;
        if (allowSign && (s[0] == '+' || s[0] == '-')) s = s.Length == 1 ? string.Empty : s.Substring(1);
        if (s.Length == 0) return false;
        for(int i = 0; i < s.Length; i++)
            if (s[i] < '0' || s[i] > '9') return false;
        return true;
    }

  • 0
    L
    //Another Short one by scanning chars.
    //Inspired by https://leetcode.com/discuss/26682/clear-java-solution-with-ifs
    public bool IsNumber(string s){
        s = s.Trim();
        bool pointSeen = false,eSeen = false, numberSeen = false, numberAfterE = true;
        for (int i = 0; i < s.Length; i++)
            if ('0' <= s[i] && s[i] <= '9'){
                numberSeen = true;
                numberAfterE = true;
            }else if (s[i] == '.'){
                if (eSeen || pointSeen) return false;
                pointSeen = true;
            }else if (s[i] == 'e'){
                if (eSeen || !numberSeen) return false;
                numberAfterE = false;
                eSeen = true;
            }else if (s[i] == '-' || s[i] == '+'){
                if (i != 0 && s[i - 1] != 'e') return false;
            }else return false;
        return numberSeen && numberAfterE;
    }

Log in to reply
 

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