LeetCode 02 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.

Example

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

翻译:
给定两个非空链表来代表两个非负数,位数按照逆序方式存储,它们的每个节点只存储单个数字。将这两数相加会返回一个新的链表。

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

示例:

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

主要是大数相加的思想,注意判断进位

/**
 * 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 || l2 == null) {
            return l1 == null ? l2 : l1;
        }
        ListNode p = new ListNode(0); 
        ListNode res = p;//定义结果链表
        int up = 0;//进位
        int value = 0;//个位数
        while(l1 != null && l2 != null){
            value = (l1.val + l2.val + up) % 10;
            up = (l1.val + l2.val + up) / 10;
            p.next = new ListNode(value);
            l1 = l1.next;
            l2 = l2.next;
            p = p.next;
            if(l1 == null && l2 == null && up == 0){ //测试用例有一个是{5}{5}结果为[0,1],当l1,l2都加完时,需要判断进位是否为0,如果不是,需要在结果链表里加上新的节点
                break;
            }
            if(l1 == null){
                l1 = new ListNode(0);//如果l1已经到最后一位,而l2还没有,那么在l1后面补零,即在数的高位补0
            }
            if(l2 == null){
                l2 = new ListNode(0);
            }
            if(up != 0){
                p.next = new ListNode(up);//如果最高位有进位
            }  
        }
        return res.next;
    }
}

猜你喜欢

转载自blog.csdn.net/zxm490484080/article/details/79580214