杰瑞科技汇

Python如何实现两数相加?

Of course! The "Add Two Numbers" problem is a classic, especially for technical interviews. It comes in a few common forms. I'll cover the most frequent one, which is a linked list problem, and then a simpler version for beginners.

Python如何实现两数相加?-图1
(图片来源网络,侵删)

The Classic "Add Two Numbers" (LeetCode #2)

This is the problem you'll most likely encounter in a coding interview. It tests your understanding of data structures, particularly linked lists, and handling edge cases.

The Problem

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Python如何实现两数相加?-图2
(图片来源网络,侵删)
  • Input: l1 = [2,4,3], l2 = [5,6,4]
  • Explanation:
    • 342 (from l1 reversed)
    • + 465 (from l2 reversed)
    • = 807
  • Output: [7,0,8] (as a linked list)
  • Explanation: The digits of the returned number are stored in reverse order.

The Data Structure: Linked List Node

First, let's define the structure of a node in a linked list.

# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

The Solution (Step-by-Step)

The core idea is to iterate through both lists simultaneously, digit by digit, just like you would do on a piece of paper. We'll need to handle three things:

  1. The sum of the current digits from l1 and l2.
  2. A carry from the previous addition (e.g., 5 + 7 = 12, so we write down 2 and carry over 1).
  3. The case where one list is longer than the other.

Here is the Python code with detailed explanations.

# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        # 1. Create a dummy node to act as the starting point of our result list.
        #    This simplifies the code by avoiding a special case for the head.
        dummy = ListNode(0)
        # 2. Initialize pointers for the current nodes in l1 and l2,
        #    a pointer for the current node in the result list,
        #    and a variable to store the carry-over value.
        current = dummy
        carry = 0
        # 3. Loop as long as there are digits in either l1 or l2, or there is a carry.
        while l1 is not None or l2 is not None or carry != 0:
            # Get the value from l1, or 0 if l1 is exhausted
            val1 = l1.val if l1 is not None else 0
            # Get the value from l2, or 0 if l2 is exhausted
            val2 = l2.val if l2 is not None else 0
            # Calculate the sum of the current digits and the carry
            total = val1 + val2 + carry
            # Determine the new carry (1 if total >= 10, otherwise 0)
            carry = total // 10
            # The digit to be added to the new list is the remainder of the sum divided by 10
            # e.g., 8 // 10 = 0, 8 % 10 = 8
            #       18 // 10 = 1, 18 % 10 = 8
            digit = total % 10
            # Create a new node with the calculated digit and link it to our result
            current.next = ListNode(digit)
            # Move the 'current' pointer to the new node
            current = current.next
            # Move the l1 and l2 pointers to the next nodes, if they exist
            if l1 is not None:
                l1 = l1.next
            if l2 is not None:
                l2 = l2.next
        # 4. The dummy node's 'next' pointer points to the head of the actual result list.
        #    We return this.
        return dummy.next

How to Use It

To test this, you need a helper function to create a linked list from a Python list and another to print it.

Python如何实现两数相加?-图3
(图片来源网络,侵删)
# Helper function to create a linked list from a list of numbers
def create_linked_list(nums):
    dummy = ListNode()
    current = dummy
    for num in nums:
        current.next = ListNode(num)
        current = current.next
    return dummy.next
# Helper function to print a linked list
def print_linked_list(head):
    result = []
    current = head
    while current:
        result.append(str(current.val))
        current = current.next
    print(" -> ".join(result))
# --- Example Usage ---
# l1 = 2 -> 4 -> 3 (represents 342)
# l2 = 5 -> 6 -> 4 (represents 465)
# Expected output: 7 -> 0 -> 8 (represents 807)
l1_list = [2, 4, 3]
l2_list = [5, 6, 4]
l1 = create_linked_list(l1_list)
l2 = create_linked_list(l2_list)
solver = Solution()
result_head = solver.addTwoNumbers(l1, l2)
print("Input l1:")
print_linked_list(l1)
print("\nInput l2:")
print_linked_list(l2)
print("\nOutput:")
print_linked_list(result_head)

Simpler Version: Adding Two Numbers in Python (Lists or Integers)

If you're just starting with Python, you might be thinking of a simpler problem: adding two numbers that are stored in standard Python lists or just as integers.

Adding Two Integers

This is the most straightforward case.

# Define two numbers
num1 = 15
num2 = 27
# Add them using the '+' operator
sum_result = num1 + num2
print(f"The sum of {num1} and {num2} is {sum_result}")
# Output: The sum of 15 and 27 is 42

Adding Two Numbers from Lists (Digits in Order)

This is closer to the spirit of the linked list problem but uses Python's built-in lists. Let's assume the digits are stored in standard order (e.g., [1, 2, 3] is 123).

def add_numbers_from_lists(list1, list2):
    """
    Adds two numbers represented as lists of digits in standard order.
    """
    # Convert list of digits to a single integer
    # map(str, list1) converts each digit to a string: e.g., [1, 2, 3] -> ['1', '2', '3']
    # "".join(...) joins them into a single string: '123'
    # int() converts the string to an integer
    num1 = int("".join(map(str, list1)))
    num2 = int("".join(map(str, list2)))
    total = num1 + num2
    # Convert the sum back to a list of digits
    # map(int, str(total)) converts the string of the number back to a list of ints
    return list(map(int, str(total)))
# --- Example Usage ---
# list1 = [1, 2, 3] (represents 123)
# list2 = [4, 5, 6] (represents 456)
# Expected output: [5, 7, 9] (represents 579)
list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = add_numbers_from_lists(list1, list2)
print(f"The sum of {list1} and {list2} is {result}")
# Output: The sum of [1, 2, 3] and [4, 5, 6] is [5, 7, 9]

Adding Two Numbers from Lists (Digits in Reverse Order)

This version mimics the linked list problem's input format using lists.

def add_numbers_from_lists_reverse(list1, list2):
    """
    Adds two numbers represented as lists of digits in REVERSE order.
    """
    # The logic is the same as the previous function, but the input format is different.
    # The conversion process remains identical.
    num1 = int("".join(map(str, list1)))
    num2 = int("".join(map(str, list2)))
    total = num1 + num2
    # Convert the sum back to a list of digits
    return list(map(int, str(total)))
# --- Example Usage ---
#
分享:
扫描分享到社交APP
上一篇
下一篇