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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

eg:

   2 4 3
 + 5 6 4
 = 7 0 8

   9 9 9
 + 8 1
 = 7 1 0 1

维护dummy, curt Node, while循环来计算从高到低数位上的加法,每加完一次l1 = l1.next, l2 = l2.next. 要注意用一个carry来记录是否进位,如果carry == 0 则不需要,若carry > 0(只能为1)时,要让该位的运算加上carry. 还要记得处理最后一味存在进位的情况,比如

  5 
+ 5
= 0 1

像这样的话,l1, l2已经是null了,那么就要专门来说carry > 0的情况下还得在形成的LinkedList尾巴后面跟上一个val = 1的Node.

/**
 * 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 null;
        }    
        if (l1 == null){
            return l2;
        }
        if (l2 == null){
            return l1;
        }
        ListNode dummy = new ListNode(-1);
        ListNode curt = dummy;
        int carry = 0;
        while (l1 != null && l2 != null){
            int sum = l1.val + l2.val + carry;
            int digit = sum % 10;
            carry = sum / 10;
            ListNode node = new ListNode(digit);
            curt.next = node;
            curt = curt.next;
            l1 = l1.next;
            l2 = l2.next;
        }
        
        while (l1 != null){
            int sum = l1.val + carry;
            int digit = sum % 10;
            carry = sum / 10;
            ListNode node = new ListNode(digit);
            curt.next = node;
            curt = curt.next;
            l1 = l1.next;
        }
        while (l2 != null){
            int sum = l2.val + carry;
            int digit = sum % 10;
            carry = sum / 10;ss
            ListNode node = new ListNode(digit);
            curt.next = node;
            curt = curt.next;
            l2 = l2.next;
        }
        if (carry > 0){
            ListNode node = new ListNode(1);
            curt.next = node;
        }
        return dummy.next;    
    }  
}

你可能感兴趣的:(2. Add Two Numbers)