问题
ListNode是自定义链表,通过两个ListNode对象给定两个整数,计算他们的和,并以同样方式返回:
123 + 348 = 471
解题思路
进位、补0
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode next1 = l1;
ListNode next2 = l2;
boolean isAddOne = false;
do {
if (isAddOne) {//进位判断
next1.val += 1;
isAddOne = false;
}
next1.val = next1.val + next2.val;
if (next1.val >= 10) {//是否需要进位
next1.val = next1.val % 10;
isAddOne = true;
}
// L1计算完毕,存在进位或者L2尚未计算完毕,补0
if (next1 != null && next1.next == null && ((next2 != null && next2.next != null) || isAddOne))
next1.next = new ListNode(0);
// L2计算完毕,L1尚未计算完毕,补0
if (next2 != null && next2.next == null && (next1 != null && next1.next != null))
next2.next = new ListNode(0);
next1 = next1 != null && next1.next != null ? next1.next : null;// L1判断是否还有下一节点
next2 = next2.next;
} while ((next1 != null) || (next2 != null) || isAddOne);// 直到两条链计算完毕,且无进位
return l1;
}
}