private String digit2Str(int digit) { if (digit == 0) return"Zero"; if (digit == 1) return"One"; if (digit == 2) return"Two"; if (digit == 3) return"Three"; if (digit == 4) return"Four"; if (digit == 5) return"Five"; if (digit == 6) return"Six"; if (digit == 7) return"Seven"; if (digit == 8) return"Eight"; if (digit == 9) return"Nine"; thrownewIllegalArgumentException("invalid input in digit2Str"); }

private String tenth2Str(int tenth, int digit) { if (tenth < 0 || tenth > 9 || digit < 0 || digit > 9) { thrownewIllegalArgumentException("invalid input in tenth2Str"); } if (tenth == 0) return digit2Str(digit); if (tenth == 1) return tenth2StrHelper(digit); Stringret=""; if (tenth == 2) ret = "Twenty"; if (tenth == 3) ret = "Thirty"; if (tenth == 4) ret = "Forty"; if (tenth == 5) ret = "Fifty"; if (tenth == 6) ret = "Sixty"; if (tenth == 7) ret = "Seventy"; if (tenth == 8) ret = "Eighty"; if (tenth == 9) ret = "Ninety"; if (digit != 0) { // e.g. 20 return ret + " " + digit2Str(digit); } else { return ret; } }

private String tenth2StrHelper(int digit) { // 11, 12, 13, 14, 15, 16, ... if (digit == 0) return"Ten"; if (digit == 1) return"Eleven"; if (digit == 2) return"Twelve"; if (digit == 3) return"Thirteen"; if (digit == 4) return"Fourteen"; if (digit == 5) return"Fifteen"; if (digit == 6) return"Sixteen"; if (digit == 7) return"Seventeen"; if (digit == 8) return"Eighteen"; if (digit == 9) return"Nineteen"; thrownewIllegalArgumentException("invalid input in tenth2StrHelper"); }

Time: $O(N)$ where $N$ is the number of digits. Space: $O(1)$ or $O(N)$ if we count the output String Builder.