1. 程式人生 > 其它 >牛客華為機試HJ42

牛客華為機試HJ42

原題傳送門

1. 題目描述

2. Solution

import sys

if sys.platform != "linux":
    file_in = open("input/HJ42.txt")
    sys.stdin = file_in

num1 = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten',
        'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen'
                                                                                       'nineteen']
num2 = [0, 0, 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']


def do_hundred(n, res):
    if n <= 0:
        return
    if n < 20:
        res.append(num1[n])
    else:
        res.append(num2[n // 10])
        if n % 10 != 0:
            res.append(num1[n % 10])


def do_thousand(n, res: list):
    """
    1000以內轉英文
    :param res:
    :param n:
    :return:
    """
    if n >= 100:
        res.append(num1[n // 100])
        res.append('hundred')
        if n % 100 != 0:
            res.append('and')
    do_hundred(n % 100, res)


def solve(s):
    n = int(s)
    res = []
    a = n % 1000
    b = (n // 1000) % 1000
    c = (n // 1000000) % 1000
    d = n // 1000000000

    if d > 0:
        do_thousand(d, res)
        res.append('billion')
    if c > 0:
        do_thousand(c, res)
        res.append('million')
    if b > 0:
        do_thousand(b, res)
        res.append('thousand')
    if a > 0:
        do_thousand(a, res)
    print(' '.join(res))


for line in sys.stdin:
    solve(line.strip())