[LeetCode]4 Add Two Numbers(C++,Python实现)

LeetCode OJ的第四题,如果有问题或者给我指点欢迎来信讨论ms08.shiroh@gmail.com

题目描述

You are given two linked lists representing two non-negative numbers. 
The digits are stored in reverse order and each of their nodes contain a single digit. 
Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8 
也就是给两个链表,每个链表代表一个非负数字,链表是按数字反方向存储,如642表示为链表就是2->4->6.
返回一个链表代表两数相加的结果(当然也是方向存储的)

思路

这道题目思路很简单,直接加就好了,注意判断好链表为空的情况以及进位的情况

代码

Python
def addTwoNumbers(self, l1, l2):
        if not l1 or not l2:
            return l2 if not l1 else l1
        carry = (l1.val + l2.val) / 10
        # result link
        res = ListNode((l1.val + l2.val) % 10)
        # store tmp res
        tmp_res = res
        while l1.next and l2.next:
            l1 = l1.next
            l2 = l2.next
            # add to link
            tmp_res.next = ListNode((l1.val + l2.val + carry) % 10)
            carry = (l1.val + l2.val + carry) / 10
            tmp_res = tmp_res.next
        # if l1 still left
        while l1.next:
            l1 = l1.next
            tmp_res.next = ListNode((l1.val + carry) % 10)
            carry = (l1.val + carry) / 10
            tmp_res = tmp_res.next
        # if l2 still left
        while l2.next:
            l2 = l2.next
            tmp_res.next = ListNode((l2.val + carry) % 10)
            carry = (l2.val + carry) / 10
            tmp_res = tmp_res.next
        # if stall exist carry
        if carry != 0:
            tmp_res.next = ListNode(carry)
            tmp_res = tmp_res.next
        return res

C++
class Solution {
public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
        if (l1 == NULL || l2 == NULL)
	    return l1 == NULL ? l2 : l1;
	int carry = ((l1->val + l2->val) / 10);
	ListNode* res = new ListNode((l1->val + l2->val) % 10);
	ListNode* tmp_res = res;
	while (l1->next != NULL && l2->next != NULL) {
	    l1 = l1->next;
	    l2 = l2->next;
	    // 添加结点
	    tmp_res->next = new ListNode(((l1->val + l2->val + carry) % 10));
	    carry = (l1->val + l2->val + carry) / 10;
	    tmp_res = tmp_res->next;
	}
	// 如果l1比较长,还存在剩余部分
	while (l1->next != NULL) {
	    l1 = l1->next;
	    // 添加结点
	    tmp_res->next = new ListNode(((l1->val + carry) % 10));
	    carry = (l1->val + carry) / 10;
	    tmp_res = tmp_res->next;
	}
	// 若果l2比较长,还存在剩余部分
	while (l2->next != NULL) {
	    l2 = l2->next;
	    // 添加结点
	    tmp_res->next = new ListNode(((l2->val + carry) % 10));
	    carry = (l2->val + carry) / 10;
	    tmp_res = tmp_res->next;
	}
	// 如果做完加法仍然有进位存在
	if (carry != 0){
	    tmp_res->next = new ListNode(carry);
	    tmp_res = tmp_res->next;
	}
	return res;
    }
};





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值