C++ 12 ms,Give some invalid examples,easily understand


  • 17
    W
    class Solution {
    public:
        bool isNumber(string s) {
            //"1 1"is not valid, "0x11" is not valid, "." is not valid, "2e3.1" is not valid, "2e" is not valid,"1a" is not valid,"++1" is not valid
            int n = s.size();
            if(n == 0) return false;
            int i = 0;
            int count_num = 0,count_point = 0;
            while(s[i] == ' ') i++;
            if(s[i] == '+' || s[i] == '-') i++;
            while(isdigit(s[i]) || s[i] == '.') s[i++] == '.'?count_point++:count_num++;
            if(count_point > 1 || count_num < 1) return false;
            if(s[i] == 'e'){
                i++;
                count_num = 0;count_point = 0;
                if(s[i] == '+' || s[i] == '-') i++;
                while(isdigit(s[i]) || s[i] == '.') s[i++] == '.'?count_point++:count_num++;
                if(count_point > 0 || count_num < 1) return false;
            }
            while(s[i] == ' ') i++;
            return i == n;
        }
    };

  • 0
    F

    YOU ARE A GOD!


  • 1
    S

    There is no need to count the count_point after 'e', because it`s impossible, like ''2e1.2'' it is wrong number.
    And my code runs for 8ms.

    bool isNumber(string s) {
    	if(s.empty()) return false;
    	int i=0,len=s.size(),count_point=0,count_num=0,count_e=0;
    	while(i<len && s[i]==' ') ++i;
    	if(i<len && (s[i]=='+' || s[i]=='-')) ++i;
    	while(i<len && ((s[i]>='0' && s[i]<='9') || s[i]=='.'))
    		s[i++]=='.'?++count_point:++count_num;
    	if(count_point>1 || count_num<1) return false;
    	if(i<len && s[i]=='e'){
    		++i;
    		if(i<len && (s[i]=='+' || s[i]=='-')) ++i;
    		while(i<len &&(s[i]>='0' && s[i]<='9')) {++i;++count_e;}
    		if(count_e<1) return false;
    	}
    	while(i<len && s[i]==' ') ++i;
    	return i==len;
    }

  • 0
    A

    very nice solution. clean code


Log in to reply
 

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