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

2. 两数相加

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

2. 两数相加

和归并的merge几乎一致,虽然还有下面的第二种,看起来也更简单,的那是如果面试,我肯定想到的是第一种,所以我就处理第一种了。这道题我两次过因为当进位为不为0的时候,虽然把两条链表都遍历完毕了,还是有一个节点要处理的。

class Solution {
public:
    ListNode* addTwonumbers(ListNode* l1, ListNode* l2) {
        int carry = 0;
        ListNode root = ListNode(-1);
        auto node = &root;
        while(nullptr!=l1 && nullptr!=l2)
        {
            int num = (carry + l1->val + l2->val)%10;
            carry = (carry + l1->val + l2->val)/10;
            node->next = new ListNode(num);
            node = node->next;
            l1 = l1->next;
            l2 = l2->next;
        }
        while(nullptr!=l1)
        {
            int num = (carry + l1->val)%10;
            carry = (carry + l1->val)/10;
            node->next = new ListNode(num);
            node = node->next;
            l1 = l1->next;          
        }
        while(nullptr!=l2)
        {
            int num = (carry + l2->val)%10;
            carry = (carry + l2->val)/10;
            node->next = new ListNode(num);
            node = node->next;
            l2 = l2->next;          
        }
        if(0!=carry)///<就这个,我忘了
            node->next = new ListNode(carry);
        return root.next;
    }
};

第二种

class Solution {
public:
ListNode* addTwonumbers(ListNode* l1, ListNode* l2) {
	if(NULL==l1)
		return l2;
	else if(NULL==l2)
		return l1;

	ListNode head = ListNode(-1);
	ListNode* pergodic = &head;
	int jinwei = 0;
	while(NULL!=l1 || NULL!=l2 || 0!=jinwei)
	{
		int sum = jinwei + ((NULL!=l1)?l1->val:0) + ((NULL!=l2)?l2->val:0);
		pergodic->next = new ListNode (sum%10);
		jinwei = sum/10;
		pergodic = pergodic->next;
		if(NULL!=l1)
			l1 = l1->next;
		if(NULL!=l2)
			l2 = l2->next;
	}
	return head.next;
}

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

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

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