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.

题目大意

有两个单链表,代表两个非负数,每一个节点代表一个数位,数字是反向存储的,即第一个结点表示最低位,最后一个结点表示最高位。求两个数的相加和,并且以链表形式返回。

解题思路

对两个链表都从第一个开始处理,进行相加,结果再除以10求商,作为下一位相加的进位,同时记录余数,作为本位的结果,一直处理,直到所有的结点都处理完。

class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode pre = new ListNode(0);
ListNode head = pre;
int carry = 0;
while(l1!=null || l2!=null || carry!=0){
ListNode node = new ListNode(0);
// 如何某一个链表为空,则用0代替
int sum = (l1==null? 0: l1.val) + (l2==null? 0: l2.val) + carry;
// 取余
node.val = sum % 10;
// 计算进位值
carry = sum / 10;
pre.next = node;
pre = node;
l1 = (l1==null? l1: l1.next);
l2 = (l2==null? l2: l2.next);
}
return head.next;
}
}
posted @ 2018-01-11 09:34  小丑进场  阅读(173)  评论(0)    收藏  举报