力扣刷题-热题100题-第28题(c++、python)

打印 上一主题 下一主题

主题 2014|帖子 2014|积分 6042

2. 两数相加 - 力扣(LeetCode)
https://leetcode.cn/problems/add-two-numbers/description/?envType=study-plan-v2&envId=top-100-liked
常规法

根据加法的规则,设置一个记位数,初始为0,遍历两个链表,相同位数相加并加上记位数得到终极的值,以个位数作为当前位数的和,十位数更新记位数。
  1. //c++
  2. /**
  3. * Definition for singly-linked list.
  4. * struct ListNode {
  5. *     int val;
  6. *     ListNode *next;
  7. *     ListNode() : val(0), next(nullptr) {}
  8. *     ListNode(int x) : val(x), next(nullptr) {}
  9. *     ListNode(int x, ListNode *next) : val(x), next(next) {}
  10. * };
  11. */
  12. class Solution {
  13. public:
  14.     ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
  15.     {
  16.         ListNode *head=nullptr,*tail=nullptr;
  17.         int carry=0;
  18.         while(l1||l2)
  19.         {
  20.             int n1=l1?l1->val:0;
  21.             int n2=l2?l2->val:0;
  22.             carry=n1+n2+carry;
  23.             if(!head)
  24.             {
  25.                 head=tail=new ListNode(carry%10);
  26.             }
  27.             else
  28.             {
  29.                 tail->next=new ListNode(carry%10);
  30.                 tail=tail->next;
  31.             }
  32.             carry=carry/10;
  33.             if(l1) l1=l1->next;
  34.             if(l2) l2=l2->next;
  35.         }
  36.         if(carry>0) tail->next=new ListNode(carry);
  37.         return head;
  38.     }
  39. };
  40. #python
  41. # Definition for singly-linked list.
  42. # class ListNode:
  43. #     def __init__(self, val=0, next=None):
  44. #         self.val = val
  45. #         self.next = next
  46. class Solution:
  47.     def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
  48.         if l1==None or l2==None:
  49.             return None
  50.         ans=ListNode()
  51.         a=ans
  52.         aa=0
  53.         while l1 or l2:
  54.             a1=l1.val if l1 else 0
  55.             a2=l2.val if l2 else 0
  56.             aa=aa+a1+a2
  57.             b=aa%10
  58.             aa=(aa//10)%10
  59.             c=ListNode(b)
  60.             a.next=c
  61.             a=a.next
  62.             if l1:
  63.                 l1=l1.next
  64.             if l2:
  65.                 l2=l2.next
  66.         if aa:
  67.             c=ListNode(aa)
  68.             a.next=c
  69.         return ans.next
复制代码


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

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

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

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

本版积分规则

鼠扑

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表