当前位置:网站首页>leetcode两数相加go实现
leetcode两数相加go实现
2022-07-02 04:58:00 【Jimmy_jimi】
目标:两数相加
给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
结果产出:
这里主要是考察链表操作和最后一位的进位需要考虑周全.
func addTwoNumbers(l1, l2 *ListNode) (head *ListNode) {
var tail *ListNode
carry := 0
for l1 != nil || l2 != nil {
n1, n2 := 0, 0
if l1 != nil {
n1 = l1.Val
l1 = l1.Next
}
if l2 != nil {
n2 = l2.Val
l2 = l2.Next
}
sum := n1 + n2 + carry
sum, carry = sum%10, sum/10
if head == nil {
//创建一个节点head
head = &ListNode{
Val: sum}
//头节点等于尾节点的位置
tail = head
} else {
//尾指针指向新节点的位置
tail.Next = &ListNode{
Val: sum}
//尾指针指向的尾节点
tail = tail.Next
}
}
if carry > 0 {
tail.Next = &ListNode{
Val: carry}
}
return
}
边栏推荐
- cs架构下抓包的几种方法
- One step implementation of yolox helmet detection (combined with oak intelligent depth camera)
- 农业生态领域智能机器人的应用
- Mathematical problems (number theory) trial division to judge prime numbers, decompose prime factors, and screen prime numbers
- Leetcode merge sort linked list
- June book news | 9 new books are listed, with a strong lineup and eyes closed!
- Cultivate primary and secondary school students' love for educational robots
- 记录一次Unity 2020.3.31f1的bug
- 国产全中文-自动化测试软件Apifox
- [understand one article] FD_ Use of set
猜你喜欢

Detailed process of DC-1 range construction and penetration practice (DC range Series)

2022-003arts: recursive routine of binary tree

win10 磁盘管理 压缩卷 无法启动问题

Idea automatic package import and automatic package deletion settings

Learn what definitelytyped is through the typescript development environment of SAP ui5

LM09丨费雪逆变换反转网格策略

C# 基于MQTTNet的服务端与客户端通信案例

洛谷入门3【循环结构】题单题解

How to recover deleted data in disk

数学知识——快速幂的理解及例题
随机推荐
Leetcode- insert and sort the linked list
2022-003arts: recursive routine of binary tree
Beginner crawler - biqu Pavilion crawler
Learn AI safety monitoring project from zero [attach detailed code]
6.30年终小结,学生时代结束
Super detailed pycharm tutorial
Markdown edit syntax
CorelDRAW graphics suite2022 free graphic design software
Unity particle Foundation
国产全中文-自动化测试软件Apifox
Go GC garbage collection notes (three color mark)
How to configure PostgreSQL 12.9 to allow remote connections
Common errors of dmrman offline backup
Summary of database problems
JS interview collection test question 1
6.30 year end summary, end of student age
Idea automatic package import and automatic package deletion settings
win10 磁盘管理 压缩卷 无法启动问题
Solution: the agent throws an exception error
洛谷入门3【循环结构】题单题解