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取模的方式:
int result=92103;
int l;
while(result!=0){
l=result%10;
System.out.println(l);
result=(result-result%10)/10;
}
run:
3
0
1
2
9
常规思路,死算:先把两个链表转化成数字,再相加,再从数字变成链表:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int num1=0,num2=0;
int index1=0,index2=0;
while(l1.next!=null){
num1+=(int) (l1.val* Math.pow(10,index1));
index1++;
l1=l1.next;
}
num1+=(int) (l1.val* Math.pow(10,index1));
while(l2.next!=null){
num2+=(int) (l2.val* Math.pow(10,index2));
index2++;
l2=l2.next;
}
num2+=(int) (l2.val* Math.pow(10,index2));
//得到了两个链表对应的数字
int result=num1+num2;
int mod=0,index=0;
ListNode head=new ListNode(result%10),l=head;
while(result-result%10!=0){
result=(result-result%10)/10;
l.next= new ListNode(result%10);
l=l.next;
}
return head;
}
}
但是,我在leetcode上面提交的时候,报错了:
Input:
[9]
[1,9,9,9,9,9,9,9,9,9]
Output:
[-9,-4,-6,-3,-8,-4,-7,-4,-1,-1]
Expected:
[0,0,0,0,0,0,0,0,0,0,1]
查了一下:int的取值范围为(-2147483648~2147483647),而这里sum的结果都到100万了,int的范围才21万多一点。
改成long型或许ok,但显然题目另有深意。
emmmmm,参考了一下别人的solution,真是蠢哭了,两个链表对齐直接加就是了。
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int value1=0,value2=0;
ListNode temp=new ListNode(0);
ListNode head=temp;
while(l1!=null&&l2!=null){
value1=(l1.val+l2.val+value2)%10;//value1表示本位和
value2=(l1.val+l2.val+value2)/10;//value2表示进位位和
temp.next=new ListNode(value1);
l1=l1.next;
l2=l2.next;
temp=temp.next;
if(l1==null&&l2==null){
break;
}
if(l1==null){
l1=new ListNode(0);
}
if(l2==null){
l2=new ListNode(0);
}
}
if(value2!=0){
temp.next=new ListNode(value2);
}
return head.next;
}
}