Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Integer to English Words ใน Python: แปลงตัวเลขเป็นคำอ่านภาษาอังกฤษ

แปลงตัวเลข 0 ถึง 2³¹-1 เป็นคำอ่านภาษาอังกฤษ เช่น 512 → "Five Hundred Twelve"

ขั้นตอนการแก้ปัญหา

  1. เตรียมลิสต์คำ: less_than_20 (1-19), tens (20,30,...90), thousands ("", "Thousand", "Million", "Billion")
  2. ฟังก์ชัน helper(n) แปลง 3 หลัก:
    • n == 0 → ""
    • n < 20 → less_than_20[n]
    • n < 100 → tens[n//10] + helper(n%10)
    • อื่น → less_than_20[n//100] + " Hundred " + helper(n%100)
  3. หลักหลัก: วนกลุ่ม 3 หลัก (pairs of 3 digits) ใช้ helper และต่อ thousands[i]

การติดตั้งใน Python

class Solution:
    less_than_20 = ["","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"]

    def numberToWords(self, num):
        if num == 0:
            return "Zero"
        def helper(n):
            if n == 0:
                return ""
            elif n < 20:
                return self.less_than_20[n] + " "
            elif n < 100:
                return self.tens[n//10] + " " + helper(n%10)
            else:
                return self.less_than_20[n//100] + " Hundred " + helper(n%100)
        ans = ""
        i = 0
        while num > 0:
            if num % 1000 != 0:
                ans = helper(num % 1000) + self.thousands[i] + " " + ans
            num //= 1000
            i += 1
        return ans.strip()

ob = Solution()
print(ob.numberToWords(512))        # Five Hundred Twelve
print(ob.numberToWords(7835271))    # Seven Million Eight Hundred Thirty Five Thousand Two Hundred Seventy One

อินพุต / เอาต์พุต

Input: 512, 7835271
Output: Five Hundred Twelve, Seven Million Eight Hundred Thirty Five Thousand Two Hundred Seventy One