码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode第四题,Add Two Numbers

时间:2014-08-05 00:51:58      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:des   style   color   os   strong   io   ar   代码   

题目原文:

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

题意解析:

给定两个链表表示两个非负数。数字逆序存储,每个节点包含一个单一的数字。计算两个链表表示的数的和,并以同样格式的链表的形式返还结果。

解法就是直接操作链表相加就可以了。。

代码如下:

C++

class Solution {
public:
	ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
		ListNode * ans = NULL, *last = NULL;
		int up = 0;
		while (NULL != l1 && NULL != l2) {
			int tmp = l1->val + l2->val + up;
			up = tmp / 10;
			if (NULL == last) {
				ans = new ListNode(tmp % 10);
				last = ans;
			} else
			last = pushBack(last, tmp % 10);
			l1 = l1->next;
			l2 = l2->next;
		}
		while (NULL != l1) {
			int tmp = l1->val + up;
			last = pushBack(last, tmp % 10);
			up = tmp / 10;
			l1 = l1->next;
		}
		while (NULL != l2) {
			int tmp = l2->val + up;
			last = pushBack(last, tmp % 10);
			up = tmp / 10;
			l2 = l2->next;
		}
		if (0 != up) {
			ListNode * l = new ListNode(up);
			last->next = l;
		}
		return ans;
	}

	ListNode * pushBack(ListNode * last, int val) {
		ListNode * l = new ListNode(val);
		last->next = l;
		return l;
	}
};

Python

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
 
class Solution:
    # @return a ListNode
    def addTwoNumbers(self, l1, l2):
        carry = 0; head = ListNode(0); curr = head;
        while l1 and l2:
            Sum = l1.val + l2.val + carry
            carry = Sum / 10
            curr.next = ListNode(Sum % 10)
            l1 = l1.next; l2 = l2.next; curr = curr.next
        while l1:
            Sum = l1.val + carry
            carry = Sum / 10
            curr.next = ListNode(Sum % 10)
            l1 = l1.next; curr = curr.next
        while l2:
            Sum = l2.val + carry
            carry = Sum / 10
            curr.next = ListNode(Sum % 10)
            l2 = l2.next; curr = curr.next
        if carry > 0:
            curr.next = ListNode(carry)
        return head.next


水一枚。。。。



LeetCode第四题,Add Two Numbers,布布扣,bubuko.com

LeetCode第四题,Add Two Numbers

标签:des   style   color   os   strong   io   ar   代码   

原文地址:http://blog.csdn.net/suool/article/details/38375137

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!