Algorithm


Problem Name: 273. Integer to English Words

Convert a non-negative integer num to its English words representation.

 

Example 1:

Input: num = 123
Output: "One Hundred Twenty Three"

Example 2:

Input: num = 12345
Output: "Twelve Thousand Three Hundred Forty Five"

Example 3:

Input: num = 1234567
Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

 

Constraints:

  • 0 <= num <= 231 - 1

Code Examples

#1 Code Example with C Programming

Code - C Programming


const char *tms[] = { "Billion", "Million",  "Thousand", "", "Hundred" };
const char *nx[] = { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" };
const char *n1x[] = { "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
const char *n2x[] = { "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
​
#define APPEND(STR) do { \
    strcat(p, STR); \
    l = strlen(p); \
    *(p + l) = ' '; \
    p += l + 1; \
    total += l + 1; \
    f = 1; \
} while (0)
​
char* numberToWords(int num) {
    char *buff, *p;
    int sz, l, total;
    int m, k, t, d = 1000000000;
    int f, onex;
    
    sz = 1000;
    buff = calloc(sz, sizeof(char));
    //assert(buff);
    p = buff;
    
    p[0] = 0;
    total = 0;
    
    k = num / d;
    if (k) {
        APPEND(nx[k - 1]);
        APPEND(tms[0]);
    }
    
    num = num % d;
    d = d / 1000;
    
    t = 1;
    while (num) {
        m = num / d;
        num = num % d;
        d = d / 1000;
        
        f = onex = 0;
        
        k = m / 100;
        m = m % 100;
        if (k) {
            APPEND(nx[k - 1]);
            APPEND(tms[4]);
        }
        
        k = m / 10;
        m = m % 10;
        if (k == 1) {
            onex = 1;
        } else if (k) {
            APPEND(n2x[k - 2]);
        }
        
        k = m;
        if (onex) {
            APPEND(n1x[k]);
        } else if (k) {
            APPEND(nx[k - 1]);
        }
        
        if (f && d) {
            APPEND(tms[t]);
        }
        t ++;
    }
    
    if (total == 0) {
        strcpy(buff, "Zero");
    } else {
        buff[total - 1] = 0;
    }
    
    //printf("%s\n", buff);
    
    return buff;
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
num = 123

Output

x
+
cmd
"One Hundred Twenty Three"

#2 Code Example with C++ Programming

Code - C++ Programming


class Solution { 
public:
    string numberToWords(int num) {
        if(num == 0) return "Zero";
        vector < string>thousands({"", " Thousand", " Million", " Billion"});
        string res = "";
        int i = 0;
        while(num){
            if(num % 1000) res = helper(num % 1000) + thousands[i] + (res.size() ? " " : "") + res;
            num /= 1000;
            i++;
        }
        return res;
    }
    
    string helper(int num){
        vector < string>lessThan20({"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine","Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"});
        vector<string>tens({"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"});
        if(num >= 100) return lessThan20[num / 100] + " Hundred" + (num % 100 ? " ": "") + helper(num % 100);
        else if(num >= 20) return tens[num / 10] + (num % 10 ? " ": "") + helper(num % 10);
        else return lessThan20[num];
    }
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
num = 123

Output

x
+
cmd
"One Hundred Twenty Three"

#3 Code Example with Java Programming

Code - Java Programming


class Solution {
    private final String[] belowTen = new String[] {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
    private final String[] belowTwenty = new String[] {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
    private final String[] belowHundred = new String[] {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};

    public String numberToWords(int num) {
        if (num == 0) return "Zero";
        return helper(num);
    }

    private String helper(int num) {
        String result;

        if (num  <  10) {
            result = belowTen[num];
        }
        else if (num < 20) {
            result = belowTwenty[num - 10];
        }
        else if (num  <  100) {
            result = belowHundred[num / 10] + " " + helper(num % 10);
        }
        else if (num < 1000) {
            result = helper(num / 100) + " Hundred " + helper(num % 100);
        }
        else if (num  <  1000000) {
            result = helper(num / 1000) + " Thousand " + helper(num % 1000);
        }
        else if (num < 1000000000) {
            result = helper(num / 1000000) + " Million " + helper(num % 1000000);
        }
        else {
            result = helper(num/1000000000) + " Billion " + helper(num % 1000000000);
        }

        return result.trim();
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
num = 12345

Output

x
+
cmd
"Twelve Thousand Three Hundred Forty Five"

#4 Code Example with Javascript Programming

Code - Javascript Programming


const numberToWords = function(num) {
  if (num === 0) return "Zero";
  if (num  < = 20) return translations.get(num);
  const result = [];

  for (let [value, translation] of translations) {
    const times = Math.floor(num / value);
    if (times === 0) continue;
    num -= times * value;
    if (times === 1 && value >= 100) {
      result.push("One", translation);
      continue;
    }
    if (times === 1) {
      result.push(translation);
      continue;
    }
    result.push(numberToWords(times), translation);
  }
  return result.join(" ");
};

const translations = new Map([
  [1000000000, "Billion"],
  [1000000, "Million"],
  [1000, "Thousand"],
  [100, "Hundred"],
  [90, "Ninety"],
  [80, "Eighty"],
  [70, "Seventy"],
  [60, "Sixty"],
  [50, "Fifty"],
  [40, "Forty"],
  [30, "Thirty"],
  [20, "Twenty"],
  [19, "Nineteen"],
  [18, "Eighteen"],
  [17, "Seventeen"],
  [16, "Sixteen"],
  [15, "Fifteen"],
  [14, "Fourteen"],
  [13, "Thirteen"],
  [12, "Twelve"],
  [11, "Eleven"],
  [10, "Ten"],
  [9, "Nine"],
  [8, "Eight"],
  [7, "Seven"],
  [6, "Six"],
  [5, "Five"],
  [4, "Four"],
  [3, "Three"],
  [2, "Two"],
  [1, "One"]
]);
Copy The Code & Try With Live Editor

Input

x
+
cmd
num = 12345

Output

x
+
cmd
"Twelve Thousand Three Hundred Forty Five"

#5 Code Example with Python Programming

Code - Python Programming


class Solution:
    def __init__(self):
        self.lessThan20 = ["","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"]
        self.tens = ["","Ten","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"]
        self.thousands = ["","Thousand","Million","Billion"]

    def numberToWords(self, num):
        if not num:
            return "Zero"
        res = ""
        for thousand in self.thousands:
            if num % 1000:
                res = self.helper(num%1000) + thousand + " " + res
            num //= 1000
        return res.strip()

    def helper(self, num):
        if not num:
            return ""
        elif num < 20:
            return self.lessThan20[num] + " "
        elif num < 100:
            return self.tens[num//10] + " " + self.helper(num%10)
        else:
            return self.lessThan20[num//100] + " Hundred " + self.helper(num%100)
Copy The Code & Try With Live Editor

Input

x
+
cmd
num = 1234567

Output

x
+
cmd
"One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

#6 Code Example with C# Programming

Code - C# Programming


namespace LeetCode
{
    public class _0273_IntegerToEnglishWords
    {
        public string NumberToWords(int num)
        {
            if (num == 0) return "Zero";

            int billion = num / 1000000000;
            int million = (num - billion * 1000000000) / 1000000;
            int thousand = (num - billion * 1000000000 - million * 1000000) / 1000;
            int rest = num - billion * 1000000000 - million * 1000000 - thousand * 1000;

            string result = "";
            if (billion != 0) result = ThreeDigitsToString(billion) + " Billion";
            if (million != 0)
            {
                if (!string.IsNullOrEmpty(result)) result += " ";
                result += ThreeDigitsToString(million) + " Million";
            }
            if (thousand != 0)
            {
                if (!string.IsNullOrEmpty(result)) result += " ";
                result += ThreeDigitsToString(thousand) + " Thousand";
            }
            if (rest != 0)
            {
                if (!string.IsNullOrEmpty(result)) result += " ";
                result += ThreeDigitsToString(rest);
            }
            return result;
        }


        private string OneDigitToString(int num)
        {
            switch (num)
            {
                case 1: return "One";
                case 2: return "Two";
                case 3: return "Three";
                case 4: return "Four";
                case 5: return "Five";
                case 6: return "Six";
                case 7: return "Seven";
                case 8: return "Eight";
                case 9: return "Nine";
            }
            return "";
        }

        private string TwoDigitsLessThan20ToString(int num)
        {
            switch (num)
            {
                case 10: return "Ten";
                case 11: return "Eleven";
                case 12: return "Twelve";
                case 13: return "Thirteen";
                case 14: return "Fourteen";
                case 15: return "Fifteen";
                case 16: return "Sixteen";
                case 17: return "Seventeen";
                case 18: return "Eighteen";
                case 19: return "Nineteen";
            }
            return "";
        }

        private string TenMultipleToString(int num)
        {
            switch (num)
            {
                case 2: return "Twenty";
                case 3: return "Thirty";
                case 4: return "Forty";
                case 5: return "Fifty";
                case 6: return "Sixty";
                case 7: return "Seventy";
                case 8: return "Eighty";
                case 9: return "Ninety";
            }
            return "";
        }

        private string TwoDigitsToString(int num)
        {
            if (num == 0)
                return "";
            else if (num  <  10)
                return OneDigitToString(num);
            else if (num < 20)
                return TwoDigitsLessThan20ToString(num);
            else
            {
                int tenner = num / 10;
                int rest = num - tenner * 10;
                if (rest != 0)
                    return TenMultipleToString(tenner) + " " + OneDigitToString(rest);
                else
                    return TenMultipleToString(tenner);
            }
        }

        private string ThreeDigitsToString(int num)
        {
            int hundred = num / 100;
            int rest = num - hundred * 100;
            string res = "";
            if (hundred * rest != 0)
                res = OneDigitToString(hundred) + " Hundred " + TwoDigitsToString(rest);
            else if ((hundred == 0) && (rest != 0))
                res = TwoDigitsToString(rest);
            else if ((hundred != 0) && (rest == 0))
                res = OneDigitToString(hundred) + " Hundred";
            return res;
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
num = 1234567

Output

x
+
cmd
"One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
Advertisements

Demonstration


Previous
#268 Leetcode Missing Number Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#274 Leetcode H-Index Solution in C, C++, Java, JavaScript, Python, C# Leetcode