zoukankan      html  css  js  c++  java
  • 2. Add Two Numbers

    https://leetcode.com/problems/add-two-numbers/#/description

    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 contain a single digit. Add the two numbers and return it as a linked list.

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

    Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
    Output: 7 -> 0 -> 8

    Sol:

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def addTwoNumbers(self, l1, l2):
            """
            :type l1: ListNode
            :type l2: ListNode
            :rtype: ListNode
            """
            # Initialize current node to dummy head of the returning list. 
            dummyhead = ListNode(0)
            # Initialize pp and qq to head of l1l1 and l2l2 respectively.
            p, q, curr = l1, l2, dummyhead
            # Initialize carry to 0.
            carry = 0
            
            # Loop through lists l1 and l2 until you reach both ends.
            while p or q:
                # Set x to node p's value. If p has reached the end of l1, set to 0.
                if p:
                    x = p.val
                else:
                    x = 0
                # Set y to node q's value. If q has reached the end of l2, set to 0.
                if q:
                    y = q.val
                else:
                    y = 0
                # Set sum = x + y + carrys.
                digit = carry + x + y
                # Update carry = sum / 10.
                carry = digit/10
                # Create a new node with the digit value of (sum mod 10) and set it to current node's next, then advance current node to next.
                curr.next = ListNode(digit % 10)
                curr = curr.next
                # Advance both p and q.
                if p:
                    p = p.next
                if q:
                    q = q.next
            # Check if carry =1, if so append a new node with digit 1 to the returning list.        
            if carry > 0:
                curr.next = ListNode(carry)
                
            # Return dummy head's next node.
            return dummyhead.next
  • 相关阅读:
    HDU 2842 (递推+矩阵快速幂)
    HDU 2838 (DP+树状数组维护带权排序)
    HDU 2836 (离散化DP+区间优化)
    HDU 2831 (贪心)
    HDU 2818 (矢量并查集)
    HDU 2822 (BFS+优先队列)
    HDU 3090 (贪心)
    HDU 3089 (快速约瑟夫环)
    XCOJ 1103 (LCA+树链最大子段和)
    HDU 3078 (LCA+树链第K大)
  • 原文地址:https://www.cnblogs.com/prmlab/p/7235221.html
Copyright © 2011-2022 走看看