Question:
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
解决:
题目是指将两数相加,但是数字表示逆序。相加时需要注意和大于10时需要进位,这也是代码最后部分进行判断的原因。
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode sum = new ListNode(0);
ListNode p = l1;
ListNode q = l2;
ListNode r = sum;
int carry = 0;
while(p != null || q != null){
int d1 = p != null ? p.val : 0;
int d2 = q != null ? q.val : 0;
d1 += carry + d2;
carry = d1 / 10;
r.next = new ListNode(d1 % 10);
r = r.next;
if (p != null)
p = p.next;
if (q != null)
q = q.next;
}
if (carry == 1)
r.next = new ListNode(1);
return sum.next;
}
代码地址(附测试代码):
https://github.com/shichaohao/LeetCodeUsingJava/tree/master/src/addTwoNumbers
网友评论