当前位置:网站首页>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
}
边栏推荐
- Online incremental migration of DM database
- Mouse events in JS
- Cannot activate CONDA virtual environment in vscode
- 初学爬虫-笔趣阁爬虫
- Hcip day 17
- Summary of MySQL key challenges (2)
- Virtual machine installation deepin system
- 汇编语言中的标志位:CF、PF、AF、ZF、SF、TF、IF、DF、OF
- Beginner crawler - biqu Pavilion crawler
- 06 装饰(Decorator)模式
猜你喜欢
Mapping location after kotlin confusion
Win10 disk management compressed volume cannot be started
数学知识(欧拉函数)
正大美欧4的主账户关注什么数据?
ThinkPHP kernel work order system source code commercial open source version multi user + multi customer service + SMS + email notification
[bus interface] Axi interface
MySQL table insert Chinese change? Solution to the problem of No
Acelems Expressway microgrid energy efficiency management platform and intelligent lighting solution intelligent lighting tunnel
06 decorator mode
C case of communication between server and client based on mqttnet
随机推荐
idea自動導包和自動删包設置
面试会问的 Promise.all()
关于Steam 教育的知识整理
How do I interview for a successful software testing position? If you want to get a high salary, you must see the offer
Go Chan's underlying principles
How to write a client-side technical solution
oracle 存储过程与job任务设置
Use of Baidu map
Record the bug of unity 2020.3.31f1 once
How to configure PostgreSQL 12.9 to allow remote connections
Its appearance makes competitors tremble. Interpretation of Sony vision-s 02 products
Typescript function details
Mysql表insert中文变?号的问题解决办法
MMAP zero copy knowledge point notes
Interview question: do you know the difference between deep copy and shallow copy? What is a reference copy?
Domestic all Chinese automatic test software apifox
Thinkphp Kernel wo system source Commercial Open source multi - user + multi - Customer Service + SMS + email notification
National all Chinese Automatic Test Software apifox
June book news | 9 new books are listed, with a strong lineup and eyes closed!
Lay the foundation for children's programming to become a basic discipline