Created
July 20, 2014 21:10
-
-
Save jingz8804/f934e7d09b933da1486c to your computer and use it in GitHub Desktop.
#ctci
This file contains 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
public class NumToEnglish{ | |
// a number like 1,897,234 can be considered as | |
// 1 million 897 thousand 234 | |
// we can divide them into several 3 digits sequence and insert | |
// thousand or million in between | |
// private String[] digits = {"One", ..., "Nine"}; | |
// private String[] tens = {"Ten", ..., "Ninety"}; | |
// private String[] teens = {"Eleven", ..., "Nineteen"}; | |
// private String[] bigs = {"", "Thousand", "Million"}; | |
public String convertNum(int num){ | |
if(num == 0) return "Zero"; | |
if(num < 0) return "Negative " + convertNum(-1 * num); | |
int count = 0; // how many 3 digits we have | |
String str = ""; | |
while(num > 0){ | |
str = convertNum100(num % 1000) + bigs[count] + " " + str; | |
count++; | |
num = num / 1000; | |
} | |
return str; | |
} | |
private String convertNum100(int num){ | |
String str = ""; | |
if(num >= 100){ | |
str = digits[num / 100 - 1] + " Hundred "; | |
num = num % 100; | |
} | |
if(num >= 11 && num <= 19){ | |
str += teens[num - 11] + " "; | |
}else if(num == 10 || num >= 20){ | |
str += tens[num / 10 - 1] + " "; | |
num = num % 10; | |
} | |
if(num > 0) str += digits[num - 1] + " "; | |
return str; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment