I was experimenting with lists, sets, and finally maps when I spotted a pattern in my code to make it recursive. Now I haven't used recursion much in the past or at work and I was very excited to have something that does recursion.
I have this recursive method that takes in an Integer
and returns a string representation of the Integer
by reading two HashMap
s.
For example representation(11) will be Eleven OR representation(89) will be Eighty-Nine, ect.
I have arranged to handle up to 999,999. Are there any improvements I could make to this current implementation to handle things more efficiently/speedily?
public String representation(Integer num) {
StringBuffer numRep = new StringBuffer();
StringBuffer hundred = new StringBuffer("Hundred");
StringBuffer thousand = new StringBuffer("Thousand");
//The case for anything less than 20; 0-19
if (num < 20) {
numRep.append(genNumMap.get(num));
//The case for any integer less than 100; 20-99
} else if (num < 100) {
int temp = num % 10;
if (temp == 0) {
numRep.append(greaterNumMap.get(num));
} else {
numRep.append(greaterNumMap.get(num - temp) + "-"
+ representation(temp));
}
//The case for any integer less than 1000, covers the hundreds; 100-999
} else if (num < 1000) {
int temp = num % 100;
if (temp == 0) {
numRep.append(representation(num / 100) + "-" + hundred);
} else {
numRep.append(representation((num - temp) / 100) + "-" + hundred
+ "-" + representation(temp));
}
//The case for any integer less that one million, covers the thousands; 1,000 - 999,999
} else if (num < 1000000) {
int temp = num % 1000;
if (temp == 0) {
numRep.append(representation(num / 1000) + "-" + thousand);
} else {
numRep.append(representation((num - temp) / 1000) + "-" + thousand
+ "-" + representation(temp));
}
} else if (num > 1000000){
numRep.append("Sorry, this number is too large");
JOptionPane.showMessageDialog(null, "Sorry, this number is too large\n"+"Integers 0 through 999,999 are exceptable.");
}
return numRep.toString();
}
StringBuilder
instead ofStringBuffer
, that is a little bit faster. \$\endgroup\$