273. Integer to English Words
leetcode hard
Task
Преобразуйте неотрицательное целое число num в его словесное представление на английском языке.
Пример:
Input: num = 123
Output: "One Hundred Twenty Three"
C# solution
matched/originalpublic class Solution {
private string[] belowTwenty = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
private string[] tens = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
private string[] thousands = {"", "Thousand", "Million", "Billion"};
public string NumberToWords(int num) {
if (num == 0) return "Zero";
int i = 0;
string result = "";
while (num > 0) {
if (num % 1000 != 0) {
result = Helper(num % 1000) + thousands[i] + " " + result;
}
num /= 1000;
i++;
}
return result.Trim();
}
private string Helper(int num) {
if (num == 0) return "";
else if (num < 20) return belowTwenty[num] + " ";
else if (num < 100) return tens[num / 10] + " " + Helper(num % 10);
else return belowTwenty[num / 100] + " Hundred " + Helper(num % 100);
}
}C++ solution
auto-draft, review before submit#include <bits/stdc++.h>
using namespace std;
// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
private vector<string> belowTwenty = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
private vector<string> tens = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
private vector<string> thousands = {"", "Thousand", "Million", "Billion"};
public string NumberToWords(int num) {
if (num == 0) return "Zero";
int i = 0;
string result = "";
while (num > 0) {
if (num % 1000 != 0) {
result = Helper(num % 1000) + thousands[i] + " " + result;
}
num /= 1000;
i++;
}
return result.Trim();
}
private string Helper(int num) {
if (num == 0) return "";
else if (num < 20) return belowTwenty[num] + " ";
else if (num < 100) return tens[num / 10] + " " + Helper(num % 10);
else return belowTwenty[num / 100] + " Hundred " + Helper(num % 100);
}
}Java solution
matched/originalclass Solution {
private final String[] belowTwenty = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
private final String[] tens = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
private final String[] thousands = {"", "Thousand", "Million", "Billion"};
public String numberToWords(int num) {
if (num == 0) return "Zero";
int i = 0;
String result = "";
while (num > 0) {
if (num % 1000 != 0) {
result = helper(num % 1000) + thousands[i] + " " + result;
}
num /= 1000;
i++;
}
return result.trim();
}
private String helper(int num) {
if (num == 0) return "";
else if (num < 20) return belowTwenty[num] + " ";
else if (num < 100) return tens[num / 10] + " " + helper(num % 10);
else return belowTwenty[num / 100] + " Hundred " + helper(num % 100);
}
}JavaScript solution
matched/originalvar numberToWords = function(num) {
if (num === 0) return "Zero";
const belowTwenty = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"];
const tens = ["", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"];
const thousands = ["", "Thousand", "Million", "Billion"];
let result = "";
let i = 0;
while (num > 0) {
if (num % 1000 !== 0) {
result = helper(num % 1000) + thousands[i] + " " + result;
}
num = Math.floor(num / 1000);
i++;
}
return result.trim();
};
function helper(num) {
const belowTwenty = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"];
const tens = ["", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"];
if (num === 0) return "";
else if (num < 20) return belowTwenty[num] + " ";
else if (num < 100) return tens[Math.floor(num / 10)] + " " + helper(num % 10);
else return belowTwenty[Math.floor(num / 100)] + " Hundred " + helper(num % 100);
}Python solution
matched/originalclass Solution:
def numberToWords(self, num: int) -> str:
if num == 0:
return "Zero"
def helper(n):
if n == 0:
return ""
elif n < 20:
return below_twenty[n] + " "
elif n < 100:
return tens[n // 10] + " " + helper(n % 10)
else:
return below_twenty[n // 100] + " Hundred " + helper(n % 100)
below_twenty = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
tens = ["", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
thousands = ["", "Thousand", "Million", "Billion"]
result = ""
i = 0
while num > 0:
if num % 1000 != 0:
result = helper(num % 1000) + thousands[i] + " " + result
num //= 1000
i += 1
return result.strip()Go solution
matched/originalpackage main
import (
"strings"
"strconv"
)
func numberToWords(num int) string {
if num == 0 {
return "Zero"
}
belowTwenty := []string{"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}
tens := []string{"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}
thousands := []string{"", "Thousand", "Million", "Billion"}
var result string
i := 0
for num > 0 {
if num%1000 != 0 {
result = helper(num%1000, belowTwenty, tens) + thousands[i] + " " + result
}
num /= 1000
i++
}
return strings.TrimSpace(result)
}
func helper(num int, belowTwenty, tens []string) string {
if num == 0 {
return ""
} else if num < 20 {
return belowTwenty[num] + " "
} else if num < 100 {
return tens[num/10] + " " + helper(num%10, belowTwenty, tens)
} else {
return belowTwenty[num/100] + " Hundred " + helper(num%100, belowTwenty, tens)
}
}Explanation
Algorithm
1️⃣
Обработка чисел до 20 и кратных 10 до 90:
Создать массивы или словари для чисел от 1 до 19 и для кратных 10 от 20 до 90.
Если число попадает в эти диапазоны, сразу вернуть соответствующее словесное представление.
2️⃣
Обработка сотен, тысяч, миллионов и миллиардов:
Разделить число на группы по три цифры (единицы, тысячи, миллионы, миллиарды).
Для каждой группы сформировать словесное представление с использованием рекурсивной функции для чисел от 1 до 999.
3️⃣
Формирование окончательного результата:
Собрать словесное представление всех групп, добавив соответствующие суффиксы (тысячи, миллионы, миллиарды).
Соединить все части в одну строку, удалив лишние пробелы.
😎