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

แปลงฐาน 3 เป็นจำนวนเต็มใน Python

ภาพรวม

โจทย์แปลงสตริงที่เป็นตัวเลขฐาน 3 (base 3, ตัวเลข 0,1,2) เป็นจำนวนเต็มฐาน 10

ตัวอย่าง

อินพุต: "10122" (ฐาน 3)

คำนวณ: 1×3⁴ + 0×3³ + 1×3² + 2×3¹ + 2×3⁰ = 81 + 0 + 9 + 6 + 2 = 98

อัลกอริทึม (Horner's Method)

ans = 0
for digit in s:
    ans = 3 * ans + digit

ขั้นตอนสำหรับ "10122":

  1. ans = 3×0 + 1 = 1
  2. ans = 3×1 + 0 = 3
  3. ans = 3×3 + 1 = 10
  4. ans = 3×10 + 2 = 32
  5. ans = 3×32 + 2 = 98

โค้ด Python

class Solution:
    def solve(self, s):
        ans = 0
        for c in map(int, s):
            ans = 3 * ans + c
        return ans

ob = Solution()
print(ob.solve("10122"))

วิธีอื่น: int() built-in

int("10122", 3)  # 98

ผลลัพธ์

98