LeetCode学习笔记1

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;
	    	
    
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值