python 2两数相加

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 2两数相加相关的知识,希望对你有一定的参考价值。

package main

import (
	"fmt"
)

func main() {
	l1 := &ListNode{
		Val:  1,
		Next: nil,
	}
	l2 := &ListNode{
		Val: 9,
		Next: &ListNode{
			Val:  9,
			Next: nil,
		},
	}
	fmt.Println(l1, l2)
	fmt.Println(addTwoNumbers(l1, l2))
}
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
	carry := 0
	res := new(ListNode)
	cur := res
	for l1 != nil || l2 != nil {
		v1 := 0
		if l1 != nil {
			v1 = l1.Val
			l1 = l1.Next
		}
		v2 := 0
		if l2 != nil {
			v2 = l2.Val
			l2 = l2.Next
		}
		sum := v1 + v2 + carry
		node := &ListNode{Val: sum % 10}
		cur.Next = node
		cur = node
		carry = sum / 10
	}
	if carry > 0 {
		node := &ListNode{Val: carry}
		cur.Next = node
	}
	return res.Next
}

type ListNode struct {
	Val  int
	Next *ListNode
}

func (l ListNode) String() string {
	cur := &l
	res := ""
	for cur != nil {
		res += fmt.Sprintf("%d-", cur.Val)
		cur = cur.Next
	}
	return res
}
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        carry = 0
        res = ListNode(0)
        cur = res
        while l1 or l2 :
            v1,v2 = 0,0
            if l1 :
                v1 = l1.val
                l1 = l1.next
            if l2:
                v2 = l2.val
                l2 = l2.next
            sum = v1 + v2 + carry
            cur.next = ListNode(sum % 10)
            carry = sum // 10
            cur = cur.next
        if carry > 0 :
            cur.next = ListNode(carry)
        return res.next

以上是关于python 2两数相加的主要内容,如果未能解决你的问题,请参考以下文章

Python版[leetcode]2. 两数相加(难度中等)

Python两数相加

leetcode No.2 两数相加 (python3实现)

2_两数相加

C++&Python 描述 LeetCode 2.两数相加

2. 两数相加