- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 32 lines of Java from the credited upstream file 273.java.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public String numberToWords(int num) {3 return num == 0 ? "Zero" : helper(num);4 }5 6 private final String[] belowTwenty = {"", "One", "Two", "Three", "Four",7 "Five", "Six", "Seven", "Eight", "Nine",8 "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen",9 "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};10 private final String[] tens = {"", "", "Twenty", "Thirty", "Forty",11 "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};12 13 private String helper(int num) {14 StringBuilder s = new StringBuilder();15 16 if (num < 20)17 s.append(belowTwenty[num]);18 else if (num < 100)19 s.append(tens[num / 10]).append(" ").append(belowTwenty[num % 10]);20 else if (num < 1000)21 s.append(helper(num / 100)).append(" Hundred ").append(helper(num % 100));22 else if (num < 1000000)23 s.append(helper(num / 1000)).append(" Thousand ").append(helper(num % 1000));24 else if (num < 1000000000)25 s.append(helper(num / 1000000)).append(" Million ").append(helper(num % 1000000));26 else27 s.append(helper(num / 1000000000)).append(" Billion ").append(helper(num % 1000000000));28 29 return s.toString().trim();30 }31}32