Простые приложения на C#
January 6, 2024

Превратить числа в текст на английском языке

В английском языке числительные строятся примерно как в русском — числа до двадцати имеют самостоятельные имена: 0 — zero, 1 — one, 2 — two, 3 — three, 4 — four, 5 — five, 6 — six, 7 — seven, 8 — eight, 9 — nine, 10 — ten, 11 — eleven, 12 — twelve, 13 — thirteen, 14 — fourteen, 15 — fifteen, 16 — sixteen, 17 — seventeen, 18 — eighteen, 19 — nineteen.
В числах от 20 до 99 десятки и единицы записываются через дефис. Например: 24 — twenty-four, 48 — forty-eight. Десятки называются так: 20 — twenty, 30 — thirty, 40 — fourty, 50 — fifty, 60 — sixty, 70 — seventy, 80 — eighty, 90 — ninety.

Преобразуйте неотрицательное целое число num в его буквенное представление английскими словами.

Пример:

Ввод: num = 123

Вывод: “One Hundred Twenty Three”

Ввод: num = 12345

Вывод: “Twelve Thousand Three Hundred Forty Five”

Решение задачи с использованием рекурсии:

internal class Program
{
    static void Main(string[] args)
    {
        Solution solution = new();
        Console.Write("\n\n\t\tВведите число>");
        int d = Convert.ToInt32(Console.ReadLine());
        string str = solution.NumberToWords(d);
        Console.WriteLine("\t\t" + str);
        Console.ReadKey();
    }
}
public class Solution
{
    public Dictionary<int, string> dict = new Dictionary<int, string>();
    public string NumberToWords(int num)
    {

        if (num == 0) return "Zero";
        InitDict();

        var r = Convert(num);
        return r.Substring(0, r.Length - 1);
    }

    public string Convert(int num)
    {

        foreach (var key in dict.Keys)
        {
            if (num >= key)
            {
                var res = dict[key] + " " + Convert(num % key);
                if (num >= 100) res = Convert(num / key) + res;
                return res;
            }
        }

        return "";

    }

    public void InitDict()
    {
        dict.Add(1000000000, "Billion");
        dict.Add(1000000, "Million");
        dict.Add(1000, "Thousand");
        dict.Add(100, "Hundred");
        dict.Add(90, "Ninety");
        dict.Add(80, "Eighty");
        dict.Add(70, "Seventy");
        dict.Add(60, "Sixty");
        dict.Add(50, "Fifty");
        dict.Add(40, "Forty");
        dict.Add(30, "Thirty");
        dict.Add(20, "Twenty");
        dict.Add(19, "Nineteen");
        dict.Add(18, "Eighteen");
        dict.Add(17, "Seventeen");
        dict.Add(16, "Sixteen");
        dict.Add(15, "Fifteen");
        dict.Add(14, "Fourteen");
        dict.Add(13, "Thirteen");
        dict.Add(12, "Twelve");
        dict.Add(11, "Eleven");
        dict.Add(10, "Ten");
        dict.Add(9, "Nine");
        dict.Add(8, "Eight");
        dict.Add(7, "Seven");
        dict.Add(6, "Six");
        dict.Add(5, "Five");
        dict.Add(4, "Four");
        dict.Add(3, "Three");
        dict.Add(2, "Two");
        dict.Add(1, "One");

    }
}

Телеграмм канал