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.

  翻译过来就是:有两个包含非负Integer类型的LinkedList,这些数字以相反的顺序存储,每个节点都包含一个数字,要求返回一个LinkedList包含两个数字之和。你可以假设这两个数字不包含任何前导零,除了数字0本身。

  这道题目比较简单,按照咱们小学学的加法计算就可以。

  就像两个数字在纸上运算,我们是从个位算起。既然每个数字都是0,1,···,9,那么两数字之和可能‘越界‘。例如5+7=12。在这个例子中,我们设置正确的数字是2,并且把用于下一次迭代的carry设置为1。carry肯定非0即1因为两个数字之和最大为9+9+1 = 19。

  步骤如下:

一,初始化返回List的头部;

二,初始化carry = 0;

三,用p,q分别指向L1和L2的头部;

四,循环L1和L2,知道到达它们的结尾。

  1,将x设置为p的值,如果p为空,则x=0;将y设置为q的值,如果q为空,则y=0;

  2,设置 sum = x + y + carry;

  3,更新carry,使carry = sum / 10;

  4,创建新节点(值为sum % 10),加入到返回List的后面;

  5,继续迭代p和q。

五,检查carry是否等于1,如果是的话,在返回的List后面加上一个新节点,值为1。

六,返回List(头部的下一个)。

    public ListNode addTwoNumbers(ListNode a,ListNode b){
        ListNode returnListNode = new ListNode(0);
        ListNode p = a,q = b,cur = returnListNode;
        int carry = 0;
        while(p != null || q != null){
            int x = (p != null) ? p.value : 0;
            int y = (q != null) ? q.value : 0;
            int sum = x + y + carry;
            int newValue = sum % 10;
            carry = sum /10;
            cur.next = new ListNode(newValue);
            cur = cur.next;
            p = (p != null)? p.next:null;
            q = (q != null)? q.next:null;
        }
        if(carry != 0){
            cur.next = new ListNode(1);
            cur = cur.next;
        }
        return returnListNode.next;
    }

 测试:

    @org.junit.Test
    public void test(){
        ListNode a = new ListNode(2);
        ListNode tempA = a;
        tempA.next = new ListNode(4);
        tempA = tempA.next;
        tempA.next = new ListNode(3);//a为 2 -> 4 -> 3
        
        ListNode b = new ListNode(5);
        ListNode tempB = b;
        tempB.next = new ListNode(6);
        tempB = tempB.next;
        tempB.next = new ListNode(4);//b为 5 -> 6 -> 4
        
        ListNode returnNode  = addTwoNumbers(a,b);
        while(returnNode != null){
            System.out.print(returnNode.value +" ");
            returnNode = returnNode.next;
        };
    }

结果:

 

 
身体是革命的本钱,爱跑步,爱生活!
原文地址:https://www.cnblogs.com/caozx/p/8562756.html