leetcode求解两数之和

题目

输入两个链表,然后输出一个链表,链表表示的是两个数的和。举例子:输入[1,2,3], [4,5,1] 输出[5,7,4]. 因为321+154=475.
正确答案如下:

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode res_list = new ListNode();
        ListNode cur_node = res_list;
        //进位
        int jinwei =0;
        while (l1!=null || l2!=null)
        {
            // pad 0
            int x = (l1==null)? 0: l1.val;
            int y= (l2==null)? 0: l2.val;
            ListNode Sto_val = new ListNode(0);
            int sum= x+y+jinwei;
            jinwei = sum/10;
            cur_node.next = new ListNode(sum%10);
            cur_node= cur_node.next;
            // 同时遍历两个链表时的增步。
            if (l1!=null)
            {l1= l1.next;}
            if(l2!=null) {l2=l2.next;}
            // 当l1==null, l2==null的时候,进位还可能是1.

        }
        if(jinwei!=0) {cur_node.next = new ListNode(1);}
        return res_list.next;
        

    }
}

涉及到pad 0思想(遍历两个链表时,指针同时往下走,有时候会走完一个链表但是另一个链表还没遍历,这时候用pad0思想就可以避免考虑,也就是链表的长度永远等于较长的那个);以及同时遍历两个链表,当一个链表遍历完的时候,如果不判断的话,会因为赋值问题报错;还有一些特殊情况,比如最后输出的结果要比l1, l2都长。
一开始踩的坑是把这道题当作数学题,也就是通过链表来还原整数,输入给int变量。但是这样做会存在一个问题,那就是整数爆炸。仔细想想在算法题中应该很常见,是自己刷题刷少了。
赋上暴力求解的算法:

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        //遍历链表一次,放到数组里,然后组成一个integer,然后做加法。
        ListNode cur_node_1= l1;
        int cur_integer= 0;
        int cur_exp = 1;
        while(cur_node_1!=null)
        {
            cur_integer += cur_node_1.val * cur_exp;
            cur_exp *=10;
            cur_node_1= cur_node_1.next;
        }
        ListNode cur_node_2= l2;
        int cur_integer_2= 0;
        int cur_exp_2 = 1;
        while(cur_node_2!=null){
            cur_integer_2+= cur_node_2.val *cur_exp_2;
            cur_exp_2 *= 10;
            cur_node_2= cur_node_2.next;
        }
        int res_int= cur_integer+cur_integer_2;
        int cur_exp_3 = 10;
        ListNode resList = new ListNode();
        ListNode cur_resList= resList;
        while(res_int >=10)
        {
            int res_node_val =res_int%cur_exp_3;
            res_int=  res_int/cur_exp_3;
            ListNode cur_node_res = new ListNode(res_node_val);
            if (resList.next==null)  {
            resList.next= cur_node_res;
            cur_resList= resList.next;
            }
            else{
                cur_resList.next= cur_node_res;
                cur_resList= cur_resList.next;
            }   
        }
        cur_resList.next = new ListNode(res_int);
        return resList.next;
        

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值