LeetCode – Refresh – Add Two Numbers

本文介绍了一种解决两数相加问题的方法,通过链表来存储数值,并逐位相加,处理进位,最终返回结果链表。此方法适用于需要处理大数运算的场景。

Same with add binary. You can also skip delete the result pointer. But just return result->next. Depends on the interviewer.

 

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
12         if (!l1) return l2;
13         if (!l2) return l1;
14         ListNode *result = new ListNode(0);
15         ListNode *runner = result;
16         int carry = 0, sum = 0;
17         while (l1 || l2) {
18             sum = carry;
19             if (l1) {
20                 sum += l1->val;
21                 l1 = l1->next;
22             }
23             if (l2) {
24                 sum += l2->val;
25                 l2 = l2->next;
26             }
27             carry = sum/10;
28             runner->next = new ListNode(sum%10);
29             runner = runner->next;
30         }
31         if (carry) {
32             runner->next = new ListNode(carry);
33         }
34         runner = result->next;
35         delete result;
36         return runner;
37     }
38 };

 

转载于:https://www.cnblogs.com/shuashuashua/p/4346157.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值