Monday, May 7, 2012

Implement isNumber()


The code is similar to atop but here we also need to check if number is a double. We need to make sure that the string has at most one decimal point.
The key steps in writing an isNumber function are:
  • Check for sign(-) after we've checked for whitespace
  • Check if each character lies between 0 & 9
  • Make note of first decimal encountered.
  • Return false if we encounter a second decimal point
  • Return false as soon as we see a non numeric character
  • Return true otherwise.
bool isNumber(string toTest)
{
    int index =0, decimal = 0;

    //Checking for sign
    if(toTest[index] == '-')
        index++;
    
    while(index<toTest.length())
    {
        int num = toTest[index] - '0';

        //Check for numerical digit
        if(num >=0 && num <=9)
        {
            index++;
            continue;
        }

        //Check if character is a decimal point and if its the first decimal point.
        else if(toTest[index] == '.')
        {

            //Number cannot have 2 decimal points so return false.
            if(decimal)
                return false;
            else
                decimal = 1;
            index++;
        }
        else
        return false;
    }
    return true;
}

No comments:

Post a Comment