Created
February 16, 2020 02:22
-
-
Save wushbin/ecc1bd95d92b6cadb934b6393a8835fe to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Solution { | |
| String[] ones = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"}; | |
| String[] teens = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", | |
| "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; | |
| String[] tens = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", | |
| "Seventy", "Eighty", "Ninety"}; | |
| String[] ks = {"", "Thousand", "Million", "Billion"}; | |
| public String numberToWords(int num) { | |
| if (num == 0) { | |
| return "Zero"; | |
| } | |
| StringBuilder sb = new StringBuilder(); | |
| String[] tokens = new String[4]; | |
| int idx = 3; | |
| while(num > 0 && idx >= 0) { | |
| tokens[idx--] = parseHelper(num % 1000); | |
| num = num / 1000; | |
| } | |
| for (int i = 0; i < 4; i++) { | |
| if (tokens[i] != null && tokens[i].length() > 0) { | |
| if (sb.length() > 0) { | |
| sb.append(" "); | |
| } | |
| sb.append(tokens[i]).append(" ").append(ks[3 - i]); | |
| } | |
| } | |
| return sb.toString().trim(); | |
| } | |
| // most basic problem is a num with 3 digits | |
| private String parseHelper(int num) { | |
| // num -> [0, 999] | |
| if (num == 0) { | |
| return ""; | |
| } | |
| StringBuilder sb = new StringBuilder(); | |
| int[] digits = new int[3]; | |
| int idx = 2; | |
| while(num > 0) { | |
| int token = num % 10; | |
| digits[idx--] = token; | |
| num = num / 10; | |
| } | |
| if (digits[0] > 0) { | |
| sb.append(ones[digits[0]]).append(" ").append("Hundred"); | |
| } | |
| if (digits[1] >= 2) { | |
| if (sb.length() > 0) { | |
| sb.append(" "); | |
| } | |
| sb.append(tens[digits[1]]); | |
| } | |
| if (digits[1] == 1) { | |
| if (sb.length() > 0) { | |
| sb.append(" "); | |
| } | |
| sb.append(teens[digits[2]]); | |
| // no need to add ones | |
| } | |
| if (digits[1] != 1 && digits[2] > 0){ | |
| if (sb.length() > 0) { | |
| sb.append(" "); | |
| } | |
| sb.append(ones[digits[2]]); | |
| } | |
| return sb.toString(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment