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

โปรแกรมบวก 1 ให้เลขที่แสดงเป็น Digit List ใน Python

ให้ Array nums เป็นหลักของเลข (เช่น [2,5,6] = 256) บวก 1 คืน Array ใหม่

ตัวอย่าง: nums=[2,6,9] → [2,7,0]

ขั้นตอน (Simulate Addition)

  1. เริ่มจาก Index สุดท้าย
  2. ถ้า +1 ≤ 9: บวกแล้ว Break
  3. มิฉะนั้น: ตั้ง 0, Carry ไปซ้าย
  4. ถ้าล้นซ้ายสุด: Insert 1 หน้าสุด

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

def solve(nums):
    i = len(nums) - 1
    while i >= 0:
        if nums[i] + 1 <= 9:
            nums[i] += 1
            break
        else:
            nums[i] = 0
            i -= 1
    if i < 0:
        nums.insert(0, 1)
    return nums

nums = [2, 6, 9]
print(solve(nums))  # Output: [2, 7, 0]

อินพุต

[2, 6, 9]

เอาต์พุต

[2, 7, 0]