learner21
BAN USERpublic class NumToString {
private static final String[] teen_or_less = {"", "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"};
private static String convert3(int i) {
String ans = "";
if(i > 0) {
int mod100 = i % 100;
if(mod100 < 20) {
ans = NumToString.teen_or_less[mod100];
} else {
ans = NumToString.teen_or_less[i % 10];
ans = NumToString.tens[(i/10)%10] + " " + ans;
}
if(i/100 > 0) {
ans = NumToString.teen_or_less[i/100] + " hundred " + ans;
}
}
return ans.trim();
}
public static String convert(int i) throws Exception {
int level = 0;
if(i < 0) {
throw new Exception("Negative!");
}
if(i == 0) {
return "zero";
}
String ans = "";
while(i > 0) {
if(level >= NumToString.thousands.length) {
throw new Exception("Too large");
}
String t = NumToString.convert3(i % 1000);
i /= 1000;
ans = t + " " + NumToString.thousands[level] + " " + ans;
level++;
}
return ans.trim();
}
public static void test() throws Exception {
int[] t = {0, 1, 5, 10, 11, 15, 17, 19, 21, 45, 99, 100, 120, 123, 1000, 1001, 1101, 10000, 120007,
123456, 112233445};
for(int i = 0; i < t.length; i++) {
System.out.println(NumToString.convert(t[i]));
}
}
}
public static int count(int n) {
// total, not excluding more than 2 consecutive c's
int t = (int)Math.pow(2, n-1) * (2 + n);
// remove all consecutive c's of count 3 or more. Each time
// there are (n-t) + 1 possibilities of t consecutive c's, and
// in the rest of the positions, there can be at most 0 or 1 b (rest are a's)
// so its (n-t+1) options again, so multiply.
for(int i = n-2; i >= 1; i--) {
t -= (i * i);
}
return t;
}
- learner21 September 12, 2016