Skip to content

Instantly share code, notes, and snippets.

@wushbin
Created February 16, 2020 02:22
Show Gist options
  • Select an option

  • Save wushbin/ecc1bd95d92b6cadb934b6393a8835fe to your computer and use it in GitHub Desktop.

Select an option

Save wushbin/ecc1bd95d92b6cadb934b6393a8835fe to your computer and use it in GitHub Desktop.
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