给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。(逆序返回)
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
思路
(1)分别依次取出求和,相加,最后逆序取余添加到链表中。问题,溢出。改成long之后仍旧溢出。
[9]
[1,9,9,9,9,9,9,9,9,9]
输出 [8,0,0,0,0,0,0,0,0,0,1]
预期结果 [0,0,0,0,0,0,0,0,0,0,1]
(2)手动处理了进位的问题。
解法1-大数溢出
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ArrayList<ListNode> list1 = new ArrayList<>();
ArrayList<ListNode> list2 = new ArrayList<>();
long c1 =1,c2=1;
long sum1 =0,sum2=0;
while(l1 != null){
sum1 =sum1 + l1.val*c1;
c1=c1*10;
l1 = l1.next;
}
while(l2 != null){
sum2 =sum2 + l2.val*c2;
c2=c2*10;
l2 = l2.next;
}
long sum =sum1+sum2;
ListNode root = new ListNode(0);
ListNode head = root;
do{
int node = (int )sum % 10;
root.next = new ListNode(node);
root = root.next;
sum = sum/10;
}while(sum>0);
return head.next;
}
}
解法2-AC
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode pre = new ListNode(0);
ListNode cur = pre;
int carry = 0;
while(l1 != null || l2 != null) {
// 为空就补0
int x = l1 == null ? 0 : l1.val;
int y = l2 == null ? 0 : l2.val;
int sum = x + y + carry;
//进位值, 0 或者 1
carry = sum / 10;
// 相加的值
sum = sum % 10;
//存到下一个结点
cur.next = new ListNode(sum);
cur = cur.next;
//防止空指针异常
if(l1 != null)
l1 = l1.next;
if(l2 != null)
l2 = l2.next;
}
if(carry == 1) {
cur.next = new ListNode(carry);
}
return pre.next;
}
}