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

    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.

    class ListNode(object):
        def __init__(self, val, next=None):
            self.val = val
            self.next = next
    
    def add_two_nums(l1, l2):
        carry, digit = 0, 0
        head, pre = None, None
    
        while l1 != None and l2 != None:
            digit = (l1.val + l2.val) % 10
            carry = (l1.val + l2.val) / 10
            l_new = ListNode(digit)
            if not head:
                head = l_new
            else:
                pre.next = l_new
            pre = l_new
            l1 = l1.next
            l2 = l2.next
    
        while l1 != None:
            digit = (l1.val + l2.carry) % 10
            carry = (l1.val + carry) / 10
            l_new = ListNode(digit)
            if not head:
                head = l_new
            else:
                pre.next = l_new
            pre = l_new
            l1 = l1.next
    
        while l2 != None:
            digit = (carry + l2.carry) % 10
            carry = (carry + carry) / 10
            l_new = ListNode(digit)
            if not head:
                head = l_new
            else:
                pre.next = l_new
            pre = l_new
            l2 = l2.next
    
        if carry > 0:
            l_new = ListNode(carry)
            pre.next = l_new
    
        return head
    
    
    L3 = ListNode(3, ListNode(2, ListNode(1)))
    L4 = ListNode(4, ListNode(3, ListNode(2)))
    
    l_res = add_two_nums(L3, L4)
    
    while l_res != None:
        print l_res.val,
        l_res = l_res.next
  • 相关阅读:
    简单的javascript抽奖程序
    Linux 二层协议架构组织
    常用正则表达式总结
    很好的矩阵覆盖问题
    很好的求幂的题目
    不错的题目-n个数连接得到的最大值
    netstat命令介绍-要用熟
    一次完整的http事务
    Apache vs. Nginx
    Python学习-生成器
  • 原文地址:https://www.cnblogs.com/geeklove01/p/9419728.html
Copyright © 2011-2022 走看看