Integer To English Words Problem


Description

LeetCode Problem 273.

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

Example 1:

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

Example 2:

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

Example 3:

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

Example 4:

1
2
Input: num = 1234567891
Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"

Constraints:

  • 0 <= num <= 2^31 - 1


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
public:
    string digits[20] = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
    string tens[10] = {"Zero", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};

    string int2string(int n) {
        if (n >= 1000000000) {
            return int2string(n / 1000000000) + " Billion" + int2string(n % 1000000000);
        } else if (n >= 1000000) {
            return int2string(n / 1000000) + " Million" + int2string(n % 1000000);
        } else if (n >= 1000) {
            return int2string(n / 1000) + " Thousand" + int2string(n % 1000);
        } else if (n >= 100) {
            return int2string(n / 100) + " Hundred" + int2string(n % 100);
        } else if (n >= 20) {
            return  " " + tens[n / 10] + int2string(n % 10);
        } else if (n >= 1) {
            return " " + digits[n];
        } else {
            return "";
        }
    }

    string numberToWords(int num) {
        if (num == 0) {
            return "Zero";
        } else {
            string ret = int2string(num);
            return ret.substr(1, ret.length() - 1);
        }
    }
};




Related Posts

Validate IP Address Problem

LeetCode 468. Given a string queryIP, return “IPv4” if IP...

Strong Password Checker Problem

LeetCode 420. A password is considered strong if the below...

Find The Closest Palindrome Problem

LeetCode 564. Given a string n representing an integer, return...

Student Attendance Record I Problem

LeetCode 551. You are given a string s representing an...

Repeated Substring Pattern Problem

LeetCode 459. Given a string s, check if it can...

Remove K Digits Problem

LeetCode 402. Given string num representing a non-negative integer num,...