The whitespaces are really annoying...


  • 0
    public class Solution {
        String[] thousands = {"", "Thousand", "Million", "Billion"};
        String[] lessThanTwenty = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
        String[] tens = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
        public String numberToWords(int num) {
            if (num == 0) return "Zero";
            int i = 0;
            String res = "";
            while (num > 0) {
                if (num % 1000 != 0) {
                    res = helper(num % 1000) + thousands[i] + " " + res;
                }
                num /= 1000;
                i++;
            }
            return res.trim(); // 1200 => "one thousand two hundred " attention to the last whitespace comes with "hundred"
        }
        private String helper(int num) {
            if (num == 0) return "";
            if (num < 20) return lessThanTwenty[num] + " ";
            if (num < 100) return tens[num / 10] + " " + helper(num % 10);
            return lessThanTwenty[num / 100] + " Hundred" + " " + helper(num % 100); // attention to the whitespace before and after "Hundred"
        }
    }
    

Log in to reply
 

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