# Concise Java Solution

• The idea is to break n into four parts : <billion><million><thousand><remaining>, and each part is at most three digits, for example, 1234567890 breaks into 1 234 567 890. Then use the helper function nToWords to translate each of the four parts, finally combine the results

``````private String nToWords(int n) {
String[] d1 = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
String[] d1x = {"Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
String[] d10 = {"Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
int h = n/100;
int td = n%100;
int t = n/10%10;
int d = n%10;
StringBuilder sb = new StringBuilder();
if(h > 0) sb.append(d1[h]).append(" Hundred");
if(td > 10 && td < 20) {
sb.append(" ").append(d1x[td-11]);
}else {
if(t > 0) sb.append(" ").append(d10[t-1]);
if(d > 0) sb.append(" ").append(d1[d]);
}
return sb.length() == 0 ? "Zero" : sb.toString().trim();
}

public String numberToWords(int num) {
if(num < 0)
return "";
String bi = nToWords(num/(int)Math.pow(10, 9));
String mi = nToWords(num/(int)Math.pow(10, 6)%(int)Math.pow(10,3));
String th = nToWords(num/(int)Math.pow(10, 3)%(int)Math.pow(10,3));
String re = nToWords(num%1000);
StringBuilder sb = new StringBuilder();
if(!"Zero".equals(bi)) sb.append(bi).append(" Billion");
if(!"Zero".equals(mi)) sb.append(" ").append(mi).append(" Million");
if(!"Zero".equals(th)) sb.append(" ").append(th).append(" Thousand");
if(!"Zero".equals(re)) sb.append(" ").append(re);
return sb.length() == 0 ? "Zero" : sb.toString().trim();
}
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.