鱼C论坛

 找回密码
 立即注册
查看: 2084|回复: 0

[技术交流] 052:Add Two Numbers

[复制链接]
发表于 2018-6-9 02:00:33 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
题目描述:

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.


C++
  1. class Solution {  
  2. public:  
  3.     ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {  
  4.         ListNode *ret = new ListNode(0);  
  5.         ListNode *cur = ret;  
  6.         int sum = 0;  
  7.         while (1) {  
  8.             if (l1 != NULL) {  
  9.                 sum += l1->val;  
  10.                 l1 = l1->next;  
  11.             }  
  12.             if (l2 != NULL) {  
  13.                 sum += l2->val;  
  14.                 l2 = l2->next;  
  15.             }  
  16.             cur->val = sum % 10;  
  17.             sum /= 10;  
  18.             if (l1 != NULL || l2 != NULL || sum)  
  19.                 cur = (cur->next = new ListNode(0));  
  20.             else  
  21.                 break;  
  22.         }  
  23.         return ret;  
  24.     }  
  25. };  
复制代码



Python
  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. #     def __init__(self, x):
  4. #         self.val = x
  5. #         self.next = None

  6. class Solution:
  7.     def addTwoNumbers(self, l1, l2):
  8.         """
  9.         :type l1: ListNode
  10.         :type l2: ListNode
  11.         :rtype: ListNode
  12.         """
  13.         a=0
  14.         s=l1
  15.         t=l2
  16.         while s.next!=None or t.next!=None:
  17.             if s.next == None:
  18.                 s.next=ListNode(0)
  19.             if t.next == None:
  20.                 t.next=ListNode(0)
  21.             b = (s.val+t.val+a)//10
  22.             s.val = (s.val+t.val+a)%10
  23.             a=b
  24.             s=s.next
  25.             t=t.next
  26.         b = (s.val+t.val+a)//10
  27.         s.val = (s.val+t.val+a)%10
  28.         a=b
  29.         if a!=0:
  30.             s.next=ListNode(1)
  31.         return l1
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-18 08:13

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表