leetcode刷题(2)——2.两数相加

一、题目

给出两个非空的链表用来表示两个非负的整数。其中,它们各自的位数是按照逆序的方式存储的,并且它们的每个节点只能存储一位数字。

如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

二、思路

进行加法时需要考虑进位,设两个链表的结点为 head1、head2,则(head1.val + head2.val + jinwei)% 10 的结果为该位置的值,(head1.val + head2.val + jinwei)/ 10 的结果为进位。

注意两点:

  • 两个链表的长度可能不同,要注意 head1 或者 head2 为 null 的情况;
  • 最高位相加时可能产生进位,此时 head1、head2 均为 null,若进位不为 0,还要将其加至结果链表的末尾。

三、代码

/**
 * 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) {
        if(l1 == null)
            return l2;
        if(l2 == null)
            return l1;
        ListNode result = new ListNode(0);// 存储求和的结果
        ListNode temp = result;// 暂存结果链表的头结点,用于返回值
        int jinwei = 0;// 进位
        while(l1 != null && l2 != null){
            int sum = l1.val + l2.val + jinwei;
            result.next = new ListNode(sum % 10);
            result = result.next;
            jinwei = sum / 10;
            l1 = l1.next;
            l2 = l2.next;
        }
        while(l1 != null){
            int sum = l1.val + jinwei;
            result.next = new ListNode(sum % 10);
            result = result.next;
            jinwei = sum / 10;
            l1 = l1.next;
        }
        while(l2 != null){
            int sum = l2.val + jinwei;
            result.next = new ListNode(sum % 10);
            result = result.next;
            jinwei = sum / 10;
            l2 = l2.next;
        }
        if(jinwei == 1){// 最高位相加的进位,若不为0,将其加至结果链表的末尾
            result.next = new ListNode(1);
        }
        return temp.next;
    }
}
发布了56 篇原创文章 · 获赞 0 · 访问量 939

猜你喜欢

转载自blog.csdn.net/weixin_45594025/article/details/104902473