Facebook Interview Question: Write algorithm to convert nu... | Glassdoor.co.uk

## Interview Question

Senior Android Developer Interview London, England

# Write algorithm to convert number for example

16 138 832 into "sixteen million one hundred thirty eight thousand eight hundred thirty two"

0

It was hard to write under pressure. Basically, I was using HashMap. Key for integer, value for spelling. Solution you can find somewhere at leetcode

Interview Candidate on 4 Aug 2017
1

firstly use (int)(Math.log10(number) + 1) to get the number of digits in the given number. (Note: you have to handle 0 differently)
e.g 16138832 should return 8. Use this number of digits to get an idea of digit place's spelling (billion, million, thousand, hundred)

Then for each digit (0~9) I'm thinking of using the previous answer's suggestion of HashMap to get the spelling.

So I imagine there would be two HashMaps, one for getting the digit spelling (one, two, ... nine, ten, ... , nineteen), the other for the digit place spelling (billion, million, thousand, hundred, ... thirty, twenty)

Anonymous on 8 Aug 2017
0

Here is the answer. Sorry for the extra spaces :)

private static String spellNumber(String number) {

HashMap level1Num = new HashMap();
level1Num.put(1, " one ");
level1Num.put(2, " two ");
level1Num.put(3, " three ");
level1Num.put(4, " four ");
level1Num.put(5, " five ");
level1Num.put(6, " six ");
level1Num.put(7, " seven ");
level1Num.put(8, " eight ");
level1Num.put(9, " nine ");
level1Num.put(10, " ten ");
level1Num.put(11, " eleven ");
level1Num.put(12, " twelve ");
level1Num.put(13, " thirteen ");
level1Num.put(14, " fourteen ");
level1Num.put(15, " fifteen ");
level1Num.put(16, " sixteen ");
level1Num.put(17, " seventeen ");
level1Num.put(18, " eighteen ");
level1Num.put(19, " ninteen ");

HashMap level2Num = new HashMap();
level2Num.put(2, " twenty ");
level2Num.put(3, " thirty ");
level2Num.put(4, " fourty ");
level2Num.put(5, " fifty ");
level2Num.put(6, " sixty ");
level2Num.put(7, " seventy ");
level2Num.put(8, " eighty ");
level2Num.put(9, " ninty ");

String output = "";

while (number.length() &gt; 0) {

String block;

if (number.length() % 3 == 0) {
block = number.substring(0, 3);
} else {
block = number.substring(0, (number.length() % 3));
}

if (block.length() &gt; 2) {
output += level1Num.get(Integer.parseInt(block.substring(0, 1))) + " hundred ";
number = number.replace(block.subSequence(0, 1), "");
block = block.replace(block.subSequence(0, 1), "");
}

int block2 = Integer.parseInt(block);

if (block2 = 7 &amp;&amp; number.length() = 4 &amp;&amp; number.length() &lt;= 6) {
output += " thousand";
}

number = number.replace(block, "");
}

return output;
}

Mohamed Tawfik on 22 Sep 2017