Last Updated: 9 Jul, 2020

Convert Given Number To Words

Moderate
Asked in companies
OracleCoinbaseAmazon

Problem statement

You have been given an integer 'num'. Write a function to calculate descriptive word form of the number.

Use the Indian standard unit of numbering.

Example :
If the given input is 62, the output should be 'Sixty two' (without quotes).

Similarly, if the input is 1000000, the output should be 'Ten lakh'.
Input format :
The first line contains an integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow.

The first and only line of each test case or query contains the integer 'num' which is to be converted to words.
Output Format :
For each test case, return the number expressed in words.

Output for every test case will be printed in a separate line.

Note:- All letters except the first one should be small.
Note
You are not required to print anything, and it has already been taken care of. Just implement the function.
Constraints :
1 <= t <= 10^4
0 <= N <= 10^9

where 't' is the number of test cases, and 'N' is the given number.

Time Limit: 1 sec.

Approaches

01 Approach

The approach that can be used here is like school mathematics in which we divide the number into individual digits and handle them starting from most significant bit. So here is the representation of each digit of number:

1 2 3 4 5 6 7 8 9

| | | | | | | | |__ ones' place

| | | | | | | |__ __ tens' place

| | | | | | |__ __ __ hundreds' place

| | | | | |__ __ __ __ thousands' place

| | | | |__ __ __ __ __ ten thousand' place

| | | |__ __ __ __ __ __ lakh' place

| | |__ __ __ __ __ __ __ ten lakh' place

| |__ __ __ __ __ __ __ __ crore' place

|__ __ __ __ __ __ __ __ __ ten crore' place

So this representation is of max 9 digits and we will write code for max 9 digits.

Approach:

Take two arrays of string type, one for one’s place and another for tens place. Initialize them with strings corresponding to that place.

Now start from MSB and handle digits for ten crores' and one crore's places (if any), ten lakh's and one lakh's places (if any), ten thousands' and thousands' places (if any), hundreds' places and ones' and tens' places separately.

See the code for more detailed explanation.