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

แปลงจำนวนเต็มเป็นคำอ่านภาษาอังกฤษใน Python

กำหนดจำนวนเต็มระหว่าง 0 ถึง 2^31 - 1 ต้องแปลงเป็นคำอ่านภาษาอังกฤษ เช่น 512 → "Five Hundred Twelve"

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

  • สร้างลิสต์คำสำหรับตัวเลข < 20, ทศนิยม (twenty, thirty...), และหน่วยใหญ่ (thousand, million, billion)
  • ฟังก์ชัน helper(n) แปลง n < 1000 เป็นคำ
  • ฟังก์ชันหลัก: แบ่งจำนวนเป็นกลุ่มละ 3 หลัก ใช้ helper แปลงแต่ละกลุ่ม พร้อมหน่วยใหญ่

ตัวอย่างโค้ด

class Solution(object):
    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"
        ans = ""
        i = 0
        while num > 0:
            if num % 1000 != 0:
                ans = self.helper(num % 1000) + Solution.thousands[i] + " " + ans
            i += 1
            num //= 1000
        return ans.strip()
    def helper(self, n):
        if n == 0:
            return ""
        elif n < 20:
            return Solution.less_than_20[n] + " "
        elif n < 100:
            return Solution.tens[n//10] + " " + self.helper(n % 10)
        else:
            return Solution.less_than_20[n // 100] + " Hundred " + self.helper(n % 100)

ob = Solution()
print(ob.numberToWords(512))
print(ob.numberToWords(7835271))

อินพุต

512 7835271

เอาต์พุต

Five Hundred Twelve
Seven Million Eight Hundred Thirty Five Thousand Two Hundred Seventy One