黄哥Python, LeetCode 第二题两数相加代码

170 阅读1分钟
原文链接: zhuanlan.zhihu.com

来源

力扣leetcode-cn.com

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。

如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)

输出:7 -> 0 -> 8

原因:342 + 465 = 807

这个题目,有的公司只提供输入和输出,没有点明要用链表去实现,但如果你想不到要用链表,面试肯定会挂。

下面是黄哥所写的Python 代码去解决这个题目

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

# 黄哥Python培训 黄哥所写
class Solution:
   def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        carry = 0
        total = 0
        l3 = ListNode(0)
        head = l3
        while l1 is not None or l2 is not None or carry > 0:
            total = carry
            if l1 is not None:
                total += l1.val
                l1 = l1.next

            if l2 is not None:
                total += l2.val
                l2 = l2.next

            node = ListNode(total % 10)
            l3.next = node
            l3 = l3.next
            carry = total // 10
        return head.next

Go 语言代码去解决这个题目

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
// 黄哥Python培训 黄哥所写
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
    resPre := &ListNode{}
	cur := resPre
	carry := 0

	for l1 != nil || l2 != nil || carry > 0 {
		sum := carry

		if l1 != nil {
			sum += l1.Val
			l1 = l1.Next
		}

		if l2 != nil {
			sum += l2.Val
			l2 = l2.Next
		}

		carry = sum / 10

		cur.Next = &ListNode{Val: sum % 10}
		cur = cur.Next
	}

	return resPre.Next

    
}


黄哥:黄哥Python:提醒要转行当程序员的朋友,学习要分先后主次zhuanlan.zhihu.com图标黄哥:黄哥Python培训是这样训练学员的zhuanlan.zhihu.com图标