加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

2. Add Two Numbers(两个大数相加)

发布时间:2020-12-14 04:59:51 所属栏目:大数据 来源:网络整理
导读: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

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

一直两个很大的数用链表逆序表示。
比如:342,表示为:(2 -> 4 -> 3)
465,表示为:(5 -> 6 -> 4)
计算342+465=807,结果也是逆序表示为:7 -> 0 -> 8

在例如,1314+520=1834被表示为:
4->1->3->1,0->2->5, 结果为:4->3->8->1

# 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 """
        if l1 is None:
            return l2
        elif l2 is None:
            return l1
        else:          
            carry = 0
            ret =ListNode(0) #头结点
            ret_Last = ret 

            while(l1 or l2):
                sum = 0
                if(l1):
                    sum = l1.val
                    l1 = l1.next
                if(l2):
                    sum += l2.val
                    l2 = l2.next
                sum += carry  #如果有进位则加True(1),否则加False(0)
                ret_Last.next = ListNode(sum%10)
                ret_Last = ret_Last.next
                carry = (sum >= 10) #如果sum>10,则carry表示进位,True被当作1来累加
            if(carry):
                ret_Last.next =ListNode(1)
            ret_Last = ret.next
            del ret #删除头结点
            return ret_Last

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读