You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
给定两个非空链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储单个数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
进阶:
如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。
示例:
输入: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出: 7 -> 8 -> 0 -> 7
题解:此题要注意的地方在于需要用到大数算法,也就是考虑做运算的这两个单链表所表示的数非常大,那么用常规的int或者long类型相加会产生越界的问题,所以将这两个数存储在数组中,再用大数法则进行相加,再将相加的值用单链表来表示。
public static ListNode addTwoNumbers(ListNode l1, ListNode l2)
{
int [] arr1 = new int[100000]; //将第一个单链表存放在数组1中
int [] arr2 = new int[100000]; //将第二个单链表存放在数组2中
int len1 = 0;
int len2 = 0;
int i=0,j=0,k=0;
ListNode p = l1; //定义单链表结点
while( p != null )
{ //存储第一个单链表
arr1[i] = p.val ;
i++;
p = p.next;
}
len1 = i;
p = l2;
while( p != null) //存储第二个单链表
{
arr2[j] = p.val ;
j++;
p = p.next;
}
len2 = j;
i = len1-1; j=len2-1;
int res[] = new int[Math.max(len1,len2)+1]; //记录两个单链表的和
while(i >= 0 && j >= 0)
{
res[k] += arr1[i]+arr2[j];
if(res[k]>=10)
{
res[k+1] = res[k]/10;
res[k] = res[k]%10;
}
k++;
i--;
j--;
}
while(i>=0) //计算剩余的单链表
{
res[k] += arr1[i];
if(res[k]>=10)
{
res[k+1] = res[k]/10;
res[k] = res[k]%10;
}
k++;
i--;
}
while(j>=0) //计算剩余的单链表
{
res[k] += arr2[j];
if(res[k]>=10)
{
res[k+1] = res[k]/10;
res[k] = res[k]%10;
}
k++;
j--;
}
if(res[k] == 0) //判断最高位是否有进位
{
k--;
}
ListNode head = new ListNode(0); //定义返回结果的头指针,逆序遍历数组res
if(k>=0)
{
p = new ListNode(res[k]);
head = p;
k--;
}
while(k>=0) //逆序遍历数组res,将数组用单链表表示
{
ListNode q = new ListNode(res[k]);
p.next = q;
p = q;
k--;
}
return head;
}
此题看似是单链表相加,但是得考虑大数,所以其实是一道大数相加的题目,曾经在16年校招面试今日头条的时候,就被要求当场写大数相加的题目,当时还是有些问题没考虑到,希望通过这道题能够对大数加法有所了解。