2. 两数相加 - 力扣(LeetCode)https://leetcode.cn/problems/add-two-numbers/description/?envType=study-plan-v2&envId=top-100-liked
常规法
根据加法的规则,设置一个记位数,初始为0,遍历两个链表,相同位数相加并加上记位数得到终极的值,以个位数作为当前位数的和,十位数更新记位数。
- //c++
- /**
- * Definition for singly-linked list.
- * struct ListNode {
- * int val;
- * ListNode *next;
- * ListNode() : val(0), next(nullptr) {}
- * ListNode(int x) : val(x), next(nullptr) {}
- * ListNode(int x, ListNode *next) : val(x), next(next) {}
- * };
- */
- class Solution {
- public:
- ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
- {
- ListNode *head=nullptr,*tail=nullptr;
- int carry=0;
- while(l1||l2)
- {
- int n1=l1?l1->val:0;
- int n2=l2?l2->val:0;
- carry=n1+n2+carry;
- if(!head)
- {
- head=tail=new ListNode(carry%10);
- }
- else
- {
- tail->next=new ListNode(carry%10);
- tail=tail->next;
- }
- carry=carry/10;
- if(l1) l1=l1->next;
- if(l2) l2=l2->next;
- }
- if(carry>0) tail->next=new ListNode(carry);
- return head;
- }
- };
- #python
- # Definition for singly-linked list.
- # class ListNode:
- # def __init__(self, val=0, next=None):
- # self.val = val
- # self.next = next
- class Solution:
- def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
- if l1==None or l2==None:
- return None
- ans=ListNode()
- a=ans
- aa=0
- while l1 or l2:
- a1=l1.val if l1 else 0
- a2=l2.val if l2 else 0
- aa=aa+a1+a2
- b=aa%10
- aa=(aa//10)%10
- c=ListNode(b)
- a.next=c
- a=a.next
- if l1:
- l1=l1.next
- if l2:
- l2=l2.next
- if aa:
- c=ListNode(aa)
- a.next=c
- return ans.next
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |