当前位置:网站首页>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
}
边栏推荐
- Pit encountered in win11 pytorch GPU installation
- List of common bugs in software testing
- What data does the main account of Zhengda Meiou 4 pay attention to?
- Realize the function of data uploading
- [understand one article] FD_ Use of set
- Idea automatic package import and automatic package deletion settings
- How to recover deleted data in disk
- LeetCode-归并排序链表
- 初学爬虫-笔趣阁爬虫
- idea自動導包和自動删包設置
猜你喜欢
随机推荐
oracle 存储过程与job任务设置
面试会问的 Promise.all()
2022-003arts: recursive routine of binary tree
C# 基于MQTTNet的服务端与客户端通信案例
将光盘中的cda保存到电脑中
Leetcode merge sort linked list
DMA Porter
Leetcode basic programming: array
Alibaba cloud polkit pkexec local rights lifting vulnerability
Summary of main account information of zhengdaliu 4
Pytest learning ----- pytest assertion of interface automation testing
Beginner crawler - biqu Pavilion crawler
农业生态领域智能机器人的应用
Cannot activate CONDA virtual environment in vscode
Online incremental migration of DM database
農業生態領域智能機器人的應用
geotrust ov多域名ssl證書一年兩千一百元包含幾個域名?
Change deepin to Alibaba image source
Thinkphp Kernel wo system source Commercial Open source multi - user + multi - Customer Service + SMS + email notification
06 装饰(Decorator)模式