Created
November 8, 2017 23:19
-
-
Save shailrshah/cb21c8ea1d92a140e57ea4af86861985 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
private static final String[] LESS_THAN_20 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; | |
private static final String[] TENS = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; | |
private static final String[] THOUSANDS = {"", "Thousand", "Million", "Billion"}; | |
public String numberToWords(int n) { | |
if(n == 0) return "Zero" | |
StringBuilder sb = new StringBuilder(); | |
for(int i = 0; n > 0; n /= 1000, i++) { | |
int modThousand = n % 1000; | |
if(modThousand != 0) { | |
sb.insert(0, " "); | |
sb.insert(0, THOUSANDS[i]); | |
sb.insert(0, " "); | |
sb.insert(0, numberLessThanThousandToString(modThousand)); | |
} | |
} | |
return sb.toString().trim(); | |
} | |
private static String numberLessThanThousandToString(int n) { | |
if(n == 0) | |
return ""; | |
if(n < 20) | |
return LESS_THAN_20[n]; | |
StringBuilder sb = new StringBuilder(); | |
if(n < 100) { | |
sb.append(TENS[n/10]); | |
sb.append(" "); | |
sb.append(numberLessThanThousandToString(n%10)); | |
} | |
else { | |
sb.append(LESS_THAN_20[n/100]); | |
sb.append(" Hundred "); | |
sb.append(numberLessThanThousandToString(n%100)); | |
} | |
return sb.toString().trim(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment