0002-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.

示例

输入:(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) {
       ListNode tmp = null;
       ListNode result = null;

       int carry = 0;
       while (l1 != null || l2 != null || carry != 0) {
           int sum = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry;
           carry = sum / 10;

           ListNode node = new ListNode(sum % 10);
           if (tmp == null) {
               tmp = node;
               result = tmp;
           } else {
               tmp.next = node;
               tmp = tmp.next;
           }

           l1 = l1 == null ? null : l1.next;
           l2 = l2 == null ? null : l2.next;
       }

       return result;
   }
}

你可能感兴趣的:(0002-Add Two Numbers)