# Ac solution code

• Special thanks for ZarickZheng's smart C++ solution!

The basic idea is:

``````1) Group units with 3 digits: "Thousand", "Million", "Billion"
2) Deal with the number < 100, as in hundredStr function
3) Finally, unite the unit strings together
``````

JAVA Code:

``````String hundredStr(int num) {
String arr1[] = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",
"Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
String arr2[] = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};

String ret = num % 100 < 20 ? arr1[num % 100] : arr2[(num % 100) / 10] + (num % 10 != 0 ? " " + arr1[num % 10] : "");
if (num > 99) ret = arr1[num/100] + " Hundred" + (num % 100 != 0 ? " " + ret : "");
return ret;
}

public String numberToWords(int num) {
String strarr[] = {"Thousand", "Million", "Billion"};
String ret = hundredStr(num % 1000);
for (int i = 0; i < 3; i++) {
num /= 1000;
ret = num % 1000 != 0 ? hundredStr(num % 1000) + " " + strarr[i] + " " + ret: ret;
}

while (!ret.isEmpty() && ret.charAt(ret.length() - 1) == ' ')
ret = ret.substring(0, ret.length() - 1);
return ret.isEmpty() ? "Zero" : ret;
}
``````

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