[LeetCode] 2. Add Two Numbers

原题链接:https://leetcode.com/problems/add-two-numbers/

1. 题目介绍

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.

给出两个非空的链表,代表着2个非负整数。链表的第一个节点是整数的个位,第二个是十位,依次类推,顺序和整数的顺序相反。比如(2 -> 4 -> 3)代表的是整数342

求这2个非负整数的和,并且用同样的方式,使用链表表示出来。
你可以假定,这两个非负整数不会以0开头,除了0之外。

Example:

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

2. 解题思路

一共有3种情况:

  1. 相加不进位 如:12+34 = 46 没有进位情况发生
  2. 相加进位,但是结果和最大加数的位数相同: 例如 9+21 = 30,30是2位数,21和9中,最大的也是2位数
  3. 相加进位,但是总位数+1: 例如 99 + 1 = 100 ,新的结果是3位数,但是加数中的最大数99是2位数

首先遍历2个链表,将其中的数取出、求和、然后进位。

在遍历链表的时候,一开始我采用的方法是,只要有一个链表结束了,就退出循环,然后再新开一个循环遍历较长链表剩余的部分。这样做非常不方便,因此参考了LeetCode 题解,其实可以使用

if(l1 != null) 	l1 = l1.next;

来控制遍历不会超过链表的范围。使用

int n1 = (l1 == null ? 0: l1.val);

保证不会抛出异常。
因此,我就把语句

while(l1 != null  && l2 != null)

改成了

while(l1 != null  || l2 != null)

于是就方便很多了。

实现代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
		int carrybit = 0;//设置进位
		int sumbit = 0;//两个链表对应节点相加的和
		
		ListNode ans = new ListNode(0);
		ListNode temp = ans;
		
		while(l1 != null  || l2 != null) {
			int n1 = (l1 == null ? 0: l1.val);
			int n2 = (l2 == null ? 0: l2.val);
			
			sumbit = n1 + n2 + carrybit;
			carrybit = sumbit / 10;
			sumbit %= 10;
			
            temp.next = new ListNode(sumbit);
			temp = temp.next;
			
			if(l1 != null) {
				l1 = l1.next;
			}
			if(l2 != null) {
				l2 = l2.next;
			}
		}
		//如果还有进位的数,那就再最后面将这个进位补上 
		//比如 99 + 9 = 108 ,108的1就是在下面代码中补上的
		if(carrybit != 0) {
			temp.next = new ListNode(carrybit);
		}
		
		return ans.next;
    }
}

3. 参考资料

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值