《2018年2月20日》【连续132天】
标题:add two numbers;
内容:
看了一道题:
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.
给你两个非空链表,表示两个非负整数。数字以相反的顺序存储,每个节点都包含一个数字。添加这两个数字并将其作为链接列表返回。
您可以假设这两个数字不包含任何前导零,除了数字0本身。(谷歌翻译,英文我看不懂的)
一开始以为直接对链表操作,发现是对它给的单链表进行操作:
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
它是让你写一个函数,我是用递归解,解得太麻烦了,而且最后还写了两个递归函数:
class Solution {
public ListNode addten(ListNode s)
{
if(s.val >=10)
{
s.val -=10;
if(s.next !=null)
{
s.next.val++;
s.next=addten(s.next);
}
else
{
ListNode sum1 =new ListNode(1);
s.next =sum1;
}
}
return s;
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode sum =new ListNode(0);
boolean ide =false;
sum.val =l1.val+l2.val;
if(sum.val >=10)
{
sum.val -=10;
ListNode sum1 =new ListNode(1);
sum.next =sum1;
ide =true;
}
if(l1.next !=null && l2.next !=null)
{
sum.next =addTwoNumbers(l1.next,l2.next);
if(ide)
sum.next.val++;
sum.next=addten(sum.next);
}
else if(l1.next !=null)
{
sum.next =l1.next;
if(ide)
sum.next.val++;
sum.next=addten(sum.next);
}
else if(l2.next !=null)
{
sum.next =l2.next;
if(ide)
sum.next.val++;
sum.next=addten(sum.next);
}
return sum;
}
}
然后上网查找了一下别人的解法:
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int carry=0;
ListNode listNode=new ListNode(0);
ListNode p1=l1,p2=l2,p3=listNode;
while(p1!=null||p2!=null){
if(p1!=null){
carry+=p1.val;
p1=p1.next;
}
if(p2!=null){
carry+=p2.val;
p2=p2.next;
}
p3.next=new ListNode(carry%10);
p3=p3.next;
carry/=10;
}
if(carry==1)
p3.next=new ListNode(1);
return listNode.next;
}
}
这里,对于数的加减直接是用了对carry的操作,并且让它有了位数上的传递,
因为起初listNode和p3是引用一个对象,而后来p3不停的引用next,从而让操作传递,
这里返回listNod.next是因为第一个操作的结果是p3.next的val;
读一读别人的代码,还是收获良多;
睡觉了;