LeetCode第二题:Add Two Numbers

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

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

给出两个表示两个非负整数的非空链表。整数以相反的顺序存储,它们的每个节点都包含一个数字。将两个数字相加,并将其作为链接列表返回。

你可以假设这两个数字不包含任何前导零,除了第0个数字本身。

Example

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

题目本身不难,但是一定要记得最后的进位问题。下面贴下我的代码,代码量偏多,但是我认为比较好理解。

 1  public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
 2         ListNode root = new ListNode(0);
 3         ListNode cur = root;//小技巧定义结果的上一个节点,返回时返回root.next
 4         int temp = 0;       //避免要先进行一次初值的计算
 5         while (l1 != null || l2 != null) {
 6             int n1 = 0;
 7             int n2 = 0;
 8             if (l1 != null) {//因为两个数不一定一样长,当一个数为空时,
 9                 n1 = l1.val; //用0计算即可,熟练的同学完全可以用三目运算符解决。
10                 l1 = l1.next;
11             }
12             if (l2 != null) {
13                 n2 = l2.val;
14                 l2 = l2.next;
15             }
16             ListNode node = new ListNode((n1 + n2 + temp) % 10);
17             temp = (n1 + n2 + temp) / 10;
18             cur.next = node;
19             cur = node;
20         }
21         //这段代码千万不要忘记,如果最后有进位,需要添加节点。
22         //当然简洁的代码是在while循环中while (l1 != null || l2 != null||temp!=0)
23         //在循环中解决这个问题,我单独列出来,希望大家牢记这一点,如果在面试中漏掉这种情况
24         //应该会在面试官那里减分的。
25         if (temp != 0) {
26             cur.next = new ListNode(temp);
27         }
28         return root.next;
29     }

 

转载于:https://www.cnblogs.com/zhandouBlog/p/8097932.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值