Share my Java recursive solution


  • 0
    public class Solution {
      String[] lows = "Zero One Two Three Four Five Six Seven Eight Nine Ten Eleven Twelve Thirteen Fourteen Fifteen Sixteen Seventeen Eighteen Nineteen".split(" ");
      String[] tens = "Twenty Thirty Forty Fifty Sixty Seventy Eighty Ninety".split(" ");
      String[] bigs = "Hundred Thousand Million Billion".split(" ");
    
      public String convert(int n) {
        if (n < 20) 
          return lows[n];
        
        if (n < 100)
          return tens[n / 10 - 2] + helper(n % 10);
        
        if (n < 1000) 
          return lows[n / 100] + " " + bigs[0] + helper(n % 100);
        
        int m = 1000;
        
        for (int i = 1; i < bigs.length; i++, m *= 1000)
          if (n / 1000 < m)
            return convert(n / m) + " " + bigs[i] + helper(n % m);
        
        return convert(n / m) + " " + bigs[bigs.length - 1] + helper(n % m);
      }
      
      public String helper(int n) {
        return n == 0 ? "" : " " + convert(n);
      }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.