Leetcode: 2. Add Two Numbers

Leetcode: 2. Add Two Numbers

一直想用一个进位变量来存贮进位值,但老是考虑不周全,下面是我自己写的bug代码,考虑不周,因为l1或者l2都有可能为null

class Solution {
     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode listEnd = new ListNode(0);
            ListNode list = listEnd;
            
            int carry = 0;
            while (l1 != null || l2 != null) {
                int sum = 0;
                if(l1!=null) {
                    sum =carry+l1.val;
                    l1 = l1.next;
                    
                }
                if(l2!=null) {
                    sum =l2.val+sum;
                    l2 = l2.next;
                }
                
                list.next = new ListNode(sum % 10);
                carry = sum/10;
                list = list.next;
            }
            if (carry== 1)
                list.next = new ListNode(1);
            return listEnd.next;
        }
}

acccpt:https://discuss.leetcode.com/topic/799/is-this-algorithm-optimal-or-what

import java.util.Map;

public class Test2 {
     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode listEnd = new ListNode(0);   //作为最后返回的链表,返回的是next
            ListNode list = listEnd;  //一直在遍历的链表,因为list指针一直是往后移动,所以只用一个指针是完成不了任务的,必须有一个作为缓存
            int sum = 0;
         
            while (l1 != null || l2 != null) {
                sum =sum/10;     //求进位,这里就只能用这种方式。我一直在想用一个变量来存储,但往往会考虑不周
                if(l1!=null) {
                    sum =sum+l1.val;
                    l1 = l1.next;
                    
                }
                if(l2!=null) {
                    sum =sum+l2.val;
                    l2 = l2.next;
                }
                
                list.next = new ListNode(sum % 10);    //动态产生链表节点
             
                list = list.next;
            }
            if (sum / 10 == 1)      //最后的和大于10的话,则进位
                list.next = new ListNode(1);
            return listEnd.next;
        }
}

 

posted on 2017-12-11 21:15 Michael2397 阅读(...) 评论(...) 编辑 收藏

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值