Friday, January 6, 2012

Converting integers less than 100 to words

This is a classic problem in which we're given an integer less than 100 and we have to output the words corresponding to the integer's value. For instance, if input is 90, then the output is "ninety" Moreover, if the input is -99, then the output is "incorrect input"
To solve this problem, we should have arrays of unique names such as "one" and "thirteen". The reason is that other integers' names are made up of just those unique names. For example, "nine" is unique name and "ninety" is unique name while "ninety nine" is just made up of "ninety" and "nine" The trick is to arrange our array such that it is easy to access the names. Here is one of the solutions to this problem:
string spellIntLessThanOneHundred(int number)
{
  if (number >= 100 || number < 0)
    return "Incorrect Input";
  
  string tensNames[] = {"", "ten", "twenty", 
"thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety"};
  
  string lessThanTwentyNames[] = {"zero", "one", 
"two", "three", " four", "five", "six", "seven", "eight", 
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", 
"sixteen", "seventeen", "eighteen", "nineteen"};

  string result;

  //numbers >= 20
  if ((number / 10) > 1)
  {
    result = tensNames[number / 10];

    number %= 10;
    
    if (number > 0)
      result = result + " " + lessThanTwentyNames[number];
  }
  //numbers < 20
  else
    result = lessThanTwentyNames[number];

  return result;
}



Notice that we have two separate arrays of unique names, one for the numbers less than twenty and one for numbers that divisible by 10 such as 20 and 30. With this arrangement, it is very easy to access the name.
  1. Our algorithm first checks for valid input which must be less than 100 and greater or equal 0.
  2. Next, we look at the first digit. If dividing the input by 10 gives a number greater than one, the input must be greater or equal 20. By dividing the input by 10, we can extract the first digit out of the input. For example, dividing 21 by 10 gives 2 (implicit type conversion). We then use the first digit to access its name in the tensNames[] array. So, if the first digit is 2 then its name is twenty.
  3. After that, we look at the last digit. By taking the remainder of the input divided by 10, we can extract the last number. If the last number is greater than 0, then we just need to get its name from the lessThanTwentyNames[] array. For example, 21 % 10 gives 1, so its name is one and the result now becomes "twenty one". However, if the remainder equals 0, we don't add anything to the result because that input is certainly divisible by 10 and has a unique name.
  4. If dividing the input by 10 results in a number less than or equal to 1, then the input must have a unique name and less than 20. Thus, we just need to look for it in lessThanTwentyNames[] array

0 comments:

Post a Comment