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
  • 相关阅读:
    MongoDB 聚合函数及排序
    MongoDB 关系运算符及统计个数及跳过分页
    MongoDB 正则表达式查询
    MongoDB 范围查询
    MongoDB 逻辑运算符
    MongoDB数据库
    python 判断文件夹存在,不存在创建文件夹
    MySQL 数据库操作
    MySQL 数据库连接命令
    PyCharm Django 显示一个简单页面
  • 原文地址:https://www.cnblogs.com/geeklove01/p/9419728.html
Copyright © 2011-2022 走看看