leetcode 2. Add Two Numbers

https://leetcode.com/problems/add-two-numbers/

You are given two linked lists representing two non-negative numbers. 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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

思路:方法比较简单,直接将每个节点的值相加取10的余数,然后除10为进位。

 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         ListNode *t1 = l1;
13         ListNode *t2 = l2;
14         int k=0;
15         int a1,a2,t=0;
16         ListNode *pre =NULL;
17         ListNode *result = NULL;
18         while(t1&&t2) {
19              a1=t1->val;t1=t1->next;
20              a2=t2->val;t2=t2->next;
21              ListNode *temp = new ListNode((a1+a2+t)%10);
22              t = (a1+a2+t)/10;
23              if(pre) pre->next = temp;
24              else result = temp;
25              pre=temp;
26         }
27         while(t1){
28             int a = t1->val;t1=t1->next;
29             ListNode *temp = new ListNode((a+t)%10);
30             t = (a+t)/10;
31             if(pre) pre->next = temp;
32             else result = temp;
33             pre = temp;
34         }
35          while(t2){
36             int a = t2->val;t2=t2->next;
37             ListNode *temp = new ListNode((a+t)%10);
38             t = (a+t)/10;
39            if(pre) pre->next = temp;
40            else result = temp;
41             pre = temp;
42         }
43         if(t) {
44             ListNode *temp = new ListNode(t);
45             pre->next = temp;
46         }
47         return result;
48     }
49     
50 };

在leetcode上时间为36ms。

 

转载于:https://www.cnblogs.com/aiheshan/p/5695310.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值