leetcode 2.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本身。


例子:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) 相当于输入342 + 465

Output: 7 -> 0 -> 8   输出结果807

Explanation: 342 + 465 = 807.


实现原理:

leetcode 2.Add Two Numbers 两个数字相加_第1张图片

 leetcode 2.Add Two Numbers 两个数字相加_第2张图片

先定义保存数据的链表结点:

public class ListNode {
    int val;
    ListNode nextNode;
    ListNode(int val){
        this.val = val;
        this.nextNode = null;
    }
}

运算代码

public class Main{
    public ListNode addTwoNumbers(ListNode L1,ListNode L2){
        //先对输入进来的两个数进行判断,判断两个数是否合法
        if(L1==null)return L1;
        if(L2==null)return L2;
        //建立头结点
        ListNode dumy = new ListNode(0);
        //建立移动的current结点,指向当前的运算位置,还没开始进行运算,所以让其指向头结点就可以了
        ListNode current = dumy;
        //定义进位carray,比如942+89的个位为2+9=11,进位为1所以carray=1
        int carry = 0;
        //判断两个数对应的位数是否都有数
        while(L1!=null &&L2 !=null){
            //定义对应位数相加后的数,比如942+89的个位2+9=11,所以big=11
            //而对弈942+89的十位,4+8还要加上个位的进位也就是carray。
            int dig = L1.val+L2.val+carry;
            //定义当前位数的值,比如942+89的个位2+9=11,所以个位的val=1
            int val = dig%10;
            //计算进位到下一位的位数
            carry = dig/10;
            //定义存储当前位数的值的ListNode结点
            ListNode newNode = new ListNode(val);
            //current结点向结果链表保存当前计算位数的结点
            current.nextNode = newNode;
            current = current.nextNode;
            //继续运算下一位
            L1 = L1.nextNode;
            L2 = L2.nextNode;
        }
        //判断第一个数是否结束了,比如我们例的942还没结束
        while (L1!=null){
            int val = (L1.val+carry)%10;
            carry = (L1.val+carry)/10;
            current.nextNode = new ListNode(val);
            current = current.nextNode;
            L1 = L1.nextNode;
        }
        //判断第二个数是否结束,比如我们的89会先结束
        while (L2!=null){
            int val = (L2.val+carry)%10;
            carry = (L2.val+carry)/10;
            current.nextNode = new ListNode(val);
            current = current.nextNode;
            L2= L2.nextNode;
        }
//        判断最后是否还有进位,比如942+89,有千位的进位,这是还是要将这个千位添加到链表中的
        if(carry!=0)
            current.nextNode=new ListNode(carry);
        return dumy.nextNode;
    }
}

好了,本次的分享到这里就结束了 ,看完之后有任何不理解的欢迎下方留言。

如果觉得本篇对你有帮助的话,也希望您能顺手给我点个喜欢或者关注我,作为我持续创作的动力。QWQ

 

你可能感兴趣的:(leetcode(java),Leet,Code,leetcode,Add,Two,Numbers,Add,Two,Numbers,两数相加,Add,Two,Number(java),两数相加java)