Sunday, December 10, 2017

Number to Words - CTS3

You are working in a bank. Given a cheque, you have been asked to verify if the amount in words and amount in numbers are the same. Your task is to write a C program to convert the amount (i.e, the number) to words.

Input:
Input consists of an integer denoting the amount.

Output:
Print the given integer amount in words as a string.

Note:
All aplahabets are in lower case only.
The given amount is less than ten lakhs.

Sample:
1] Input: 12
    Output: twelve
2] Input: 1098
    Output: one thousand and ninety eight
3] Input: 975421
    Output: nine lakh seventy five thousand four hundred and twenty one

Solution:
#include <iostream>
using namespace std;
const string EMPTY = "";
string X[] = { EMPTY, "One ", "Two ", "Three ", "Four ", "Five ",
                                       "Six ", "Seven ", "Eight ", "Nine ", "Ten ", "Eleven ",
                                       "Twelve ", "Thirteen ", "Fourteen ", "Fifteen ",
                                       "Sixteen ", "Seventeen ", "Eighteen ", "Nineteen " };
string Y[] = { EMPTY, EMPTY, "Twenty ", "Thirty ", "Forty ", "Fifty ",
                "Sixty ", "Seventy ", "Eighty ", "Ninety " };
string convert2digit(int n, string suffix)
{
    if (n == 0)
        return EMPTY;
          if (n > 19)
                   return Y[n / 10] + X[n % 10] + suffix;
          else
                   return X[n] + suffix;
}
string numberToWords(unsigned long long int n)
{
          string res;
          res = convert2digit((n % 100), EMPTY);
          if (n > 100 && n % 100)
                   res = "and " + res;
          res = convert2digit(((n / 100) % 10), "Hundred ") + res;
          res = convert2digit(((n / 1000) % 100), "Thousand ") + res;
          res = convert2digit(((n / 100000) % 100), "Lakh, ") + res;
          res = convert2digit((n / 10000000) % 100, "Crore, ") + res;
          res = convert2digit((n / 1000000000) % 100, "Billion, ") + res;
          return res;
}
int main()
{
    int n;
    cin>>n;
          cout << numberToWords(n) << endl;
          return 0;
}
Share: