前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >No.002 Add Two Numbers

No.002 Add Two Numbers

作者头像
mukekeheart
发布2018-02-27 12:19:02
4480
发布2018-02-27 12:19:02
举报

Add Two Numbers

  • Total Accepted: 160702
  • Total Submissions: 664770
  • Difficulty: Medium

  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

  本题的思路其实很简单,两个链表的结构都是从低位到高位的顺序,税后要求返回的链表也是这样的结构。所以我们只需要依次循环两个链表,将对应位的数相加,并判断是否有进位,有进位则将进位累加到下一位即可。

代码语言:javascript
复制
 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Num2 {
10     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
11         if(l1 == null){
12             return l2 ;
13         }
14         if(l2 == null){
15             return l1 ;
16         }
17         int nextBit = (l1.val + l2.val)/10  ;
18         int curBit = (l1.val + l2.val)%10 ;
19         ListNode head = new ListNode(curBit) ;
20         ListNode temp = head ;
21         l1 = l1.next ;
22         l2 = l2.next ;
23         //当l1、l2对应位均存在时,进行计算
24         while(l1 != null && l2 != null){
25             curBit = (l1.val + l2.val + nextBit) % 10 ;
26             nextBit = (l1.val + l2.val + nextBit)/10 ;
27             ListNode node = new ListNode(curBit) ;
28             temp.next = node ;
29             temp = temp.next ;
30             l1 = l1.next ;
31             l2 = l2.next ;
32         }
33         //判断l1是否结束,没有结束继续
34         while(l1 != null){
35             curBit = (l1.val + nextBit) % 10 ;
36             nextBit = (l1.val + nextBit)/10 ;
37             ListNode node = new ListNode(curBit) ;
38             temp.next = node ;
39             temp = temp.next ;
40             l1 = l1.next ;
41         }
42         //判断l2是否结束,没有结束继续
43         while(l2 != null){
44             curBit = (l2.val + nextBit) % 10 ;
45             nextBit = (l2.val + nextBit)/10 ;
46             ListNode node = new ListNode(curBit) ;
47             temp.next = node ;
48             temp = temp.next ;
49             l2 = l2.next ;
50         }
51         //判断最后的进位位是否为0 ,不为0则需要保存下一位
52         if(nextBit != 0){
53             ListNode node = new ListNode(nextBit) ;
54             temp.next = node ;
55         }
56         return head ;        
57     }
60 }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-07-24 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Add Two Numbers
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档