• API
• FAQ
• Tools
• Archive
SHARE
TWEET

# Untitled

a guest Sep 17th, 2019 96 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. class Solution {
2.     private static String[] ONES_AND_TEENS = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
3.     private static String[] TENS = {null, "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
4.     private static String HUNDRED = "Hundred";
5.     private static String[] HIGHER_ORDERS = {null, "Thousand", "Million", "Billion"};
6.
7.     public String numberToWords(int num) {
8.         if (num < 20) {
9.             return ONES_AND_TEENS[num];
10.         }
11.
12.         Deque<String> stack = new LinkedList<>();
13.
14.         // Work from right to left
15.         int quotient = num;
16.         int i=0;
17.         while (quotient > 0) {
18.             String suffix = HIGHER_ORDERS[i];
19.             if (suffix != null) {
20.                 stack.push(suffix);
21.             }
22.             String tens = getTens(quotient);
23.             if (tens != null) {
24.                 stack.push(tens);
25.             }
26.             String hundreds = getHundreds(quotient);
27.             if (hundreds != null) {
28.                 stack.push(hundreds);
29.             }
30.             quotient = quotient / 1000;
31.             i++;
32.         }
33.
34.         return String.join(" ", stack);
35.     }
36.
37.     private static String getOnesAndTeens(int num) {
38.         return ONES_AND_TEENS[num];
39.     }
40.
41.     private static String getHundreds(int num) {
42.         String hundreds = null;
43.         int hundredsPlace = (num % 1000) / 100;
44.         if (hundredsPlace > 0) {
45.             hundreds = getOnesAndTeens(hundredsPlace) + " " + HUNDRED;
46.         }
47.
48.         return hundreds;
49.     }
50.
51.     private static String getTens(int num) {
52.         String tens = null;
53.         int remainder = num % 100;
54.         if (remainder < 20) {
55.             tens = getOnesAndTeens(remainder);
56.         } else {
57.             int tensPlace = remainder / 10;
58.             tens = TENS[tensPlace];
59.             int onesPlace = remainder % 10;
60.             if (onesPlace > 0) {
61.                 tens += " " + ONES_AND_TEENS[onesPlace];
62.             }
63.         }
64.
65.         return tens;
66.     }
67. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy.
Not a member of Pastebin yet?