栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

LeetCode2. 两数相加

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LeetCode2. 两数相加

思路

首先,要注意有进位的问题,进位的数字下一次计算也会计算,所以就用text来保存进位。在最后结束的时候,如果进位text不为空,还要在链表尾追加一个节点,其值为text。

其次,两个链表的长度不一样,一个链表遍历完了,另一个没遍历完要补0.我这里没有补0节点,而是在计算值的时候用0代替。

代码
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        
        ListNode head1 = l1;
        ListNode head2 = l2;
        ListNode res = new ListNode();
        ListNode temp = res;
        int text = 0;
        while(head1 != null || head2 != null){
            ListNode next = new ListNode();
            int n1 = head1 != null ? head1.val:0;
            int n2 = head2 != null ? head2.val:0;
            next.val = ((n1 + n2 + text)%10);
            text = (n1 + n2 + text)/10;
            if(head1 != null){
                head1 = head1.next;
            }
            if(head2 != null){
                head2 = head2.next;
            }
            temp.next = next;
            temp = next;
        }
        if(text > 0)
            temp.next = new ListNode(text);
        return res.next;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/925872.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号