In c valid the number


  • 0
    R

    Code to valid if given string is a valid the number

    bool isNumber(char* s) 
    {
    	bool hasExpDigit = false;
    	bool hasDecimalPoint = false;
    	bool hasSign = false;
    	bool IsDigitFound = false;
    	bool IsEndingSpaces = false;
    	bool hasSomeNum = false;
    
    	while (*s != '\0')
    	{
    		if (*s == ' ')
    		{
    			if (IsDigitFound || hasDecimalPoint || hasSign || hasExpDigit) IsEndingSpaces = true;
    		}
    		else if (IsEndingSpaces)
    		{
    			return false;
    		}
    		else if (*s == '.')
    		{
    			if (hasDecimalPoint || hasExpDigit) return false;
    			hasDecimalPoint = true;
    		}
    		else if ((*s == '+') || (*s == '-'))
    		{
    			if ((hasSign && !hasExpDigit) || 
    				(!hasExpDigit && (IsDigitFound || hasDecimalPoint)) ||
    				(hasExpDigit && !((*(s-1) == 'e') || (*(s - 1) == 'E'))))
    				return false;
    
    			hasSign = true;
    		}
    		else if ((*s - '0') >= 0 && (*s - '0') <= 9)
    		{
    			IsDigitFound = true;
    			hasSomeNum = true;
    
    		}
    		else if (*s == 'e' || *s == 'E')
    		{
    			if (hasExpDigit || !IsDigitFound || !hasSomeNum) return false;
    			hasExpDigit = true;
    			hasSomeNum = false;
    		}
    		else
    		{
    			return false;
    		}
    		s++;
    	}
    	return (IsDigitFound && (!hasExpDigit || hasSomeNum));
    }
    

Log in to reply
 

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