首页 > 其他 > 详细

LeetCode:2 两数相加

时间:2020-10-03 09:38:02      阅读:35      评论:0      收藏:0      [点我收藏+]
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1==null){
            return l2;
        }
        if(l2==null){
            return l1;
        }
        int t=0;
        
        ListNode res = new ListNode(0,null);
        ListNode recent = res;
        while(l1!=null||l2!=null){
            int x = l1==null?0:l1.val;
            int y = l2==null?0:l2.val;
            int temp=x+y+t;
            t = temp / 10;
            temp = temp % 10;
            ListNode n = new ListNode(temp,null);
            
            recent.next = n;
            recent = n;
            if(l1!=null)l1=l1.next;
            if(l2!=null)l2=l2.next;
        }
        if(t!=0){
            ListNode n = new ListNode(t,null);
            recent.next = n;
        }
        return res.next;
    }
}

 

LeetCode:2 两数相加

原文:https://www.cnblogs.com/dloooooo/p/13763472.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!