LeetCode学习笔记1
解析
错误的代码
思路:把题目转化成A+B的形式,但忘记考虑了链表中数合成一个数后超过long型
注意如果用java的大数是可以过的,就是麻烦一点
/**
这是错误的答案
* 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 i=1;
int a=0;
a=l1.val;
while(l1.next!=null)
{
a+=l1.next.val*Math.pow(10, i);
i++;
l1=l1.next;
}
int j=1;
int b=0;
b=l2.val;
while(l2.next!=null)
{
b+=l2.next.val*Math.pow(10, j);
j++;
l2=l2.next;
}
ListNode cur=new ListNode(0);
int c=a+b;
ListNode q=cur;
q.val=c%10;
c=c/10;
while(c>0)
{
q.next=new ListNode(c%10);
q=q.next;
c=c/10;
}
return cur;
}
}
通过的代码
模拟十进制加法运算核心
ListNode ans=new ListNode(0);
ListNode q=ans;//通过哑节点来实现链表的链接
q.next=new ListNode(sum%10);
q=q.next;
return ans.next;//注意第一个节点val值为0;
/**
* 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)
{
ListNode ans=new ListNode(0);
ListNode q=ans;
int temp=0;
while(l1!=null||l2!=null)
{
int x=l1==null? 0:l1.val;
int y=l2==null? 0:l2.val;
int sum=x+y+temp;
q.next=new ListNode(sum%10);
q=q.next;
temp=sum/10;
if(l1!=null)l1=l1.next;
if(l2!=null)l2=l2.next;
}
if(temp==1)
{
q.next=new ListNode(1);
}
return ans.next;
}
}