Skip to content

Commit e741709

Browse files
authored
Merge pull request #862 from harsh6768-svg/master
Added code for the program to convert given no to word in general question
2 parents d940c16 + 551d959 commit e741709

File tree

1 file changed

+98
-0
lines changed

1 file changed

+98
-0
lines changed
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
/* C++ program to print a given number in words. The program
2+
handles numbers from 0 to 9999
3+
Just take an example if the user privide the number
4+
INPUT-
5+
1-No of test cases
6+
1234-the given number
7+
OUTPUT-
8+
One thousand Two hundred and twenty four */
9+
#include<bits/stdc++.h>
10+
using namespace std;
11+
string one[] = { "", "one ", "two ", "three ", "four ",
12+
"five ", "six ", "seven ", "eight ",
13+
"nine ", "ten ", "eleven ", "twelve ",
14+
"thirteen ", "fourteen ", "fifteen ",
15+
"sixteen ", "seventeen ", "eighteen ",
16+
"nineteen " };
17+
18+
// strings at index 0 and 1 are not used, they is to
19+
// make array indexing simple
20+
string ten[] = { "", "", "twenty ", "thirty ", "forty ",
21+
"fifty ", "sixty ", "seventy ", "eighty ",
22+
"ninety " };
23+
/* ******* Your Functions Below ******** */
24+
25+
26+
// n is 1- or 2-digit number
27+
string numToWords(int n, string s)
28+
{
29+
string str = "";
30+
// if n is more than 19, divide it
31+
if (n > 19)
32+
str += ten[n / 10] + one[n % 10];
33+
else
34+
str += one[n];
35+
36+
// if n is non-zero
37+
if (n)
38+
str += s;
39+
40+
return str;
41+
}
42+
43+
// Function to print a given number in words
44+
string convertToWords(long n)
45+
{
46+
// stores word representation of given number n
47+
string out;
48+
49+
// handles digits at ten millions and hundred
50+
// millions places (if any)
51+
out += numToWords((n / 10000000), "crore ");
52+
53+
// handles digits at hundred thousands and one
54+
// millions places (if any)
55+
out += numToWords(((n / 100000) % 100), "lakh ");
56+
57+
// handles digits at thousands and tens thousands
58+
// places (if any)
59+
out += numToWords(((n / 1000) % 100), "thousand ");
60+
61+
// handles digit at hundreds places (if any)
62+
out += numToWords(((n / 100) % 10), "hundred ");
63+
64+
if (n > 100 && n % 100)
65+
out += "and ";
66+
67+
// handles digits at ones and tens places (if any)
68+
out += numToWords((n % 100), "");
69+
70+
return out;
71+
}
72+
int main()
73+
{
74+
int t;
75+
cin>>t;
76+
77+
while(t--)
78+
{
79+
long n ;
80+
cin>>n;
81+
82+
// convert given number in words
83+
cout << convertToWords(n) << endl;
84+
85+
86+
}
87+
}
88+
89+
/*Time complexity:
90+
Time complexity: O(1).
91+
The loop runs for a constant amount of time.
92+
Auxiliary space: O(1).
93+
As no extra space is required.
94+
Time complexity: O(1). */
95+
96+
97+
98+

0 commit comments

Comments
 (0)