Leetcode 每日一题练习 ------ 2582. 递枕头 2. 两数相加

Leetcode 每日一题练习继续讨论:

在各位佬友的支持下成为类别专家,感谢各位佬友的支持,以后一定继续为大家产出优质内容

2582. 递枕头
2582. Pass the Pillow

题解

本题是简单题, 使用time对n-1(4个人只需传承3次即可到最后一人)求模和求商, 商的奇偶可以决定传递的起点是队首还是队尾, 求模得到的余数可以决定从本次传递起点开始传递了几次. 再使用对应的传递起点计算当前传递到哪个人.

代码

func passThePillow(n int, time int) int {
    label := time % (n-1)
    dir := time / (n-1)
    if dir % 2 == 1{
        return n - label
    }else{
        return label + 1
    }
}

2. 两数相加
2. Add Two Numbers

题解

本题在两个链表中较长的链表上直接加上另一个链表的中对应节点的值并用标志位标记进位. 当一个链表遍历结束时将另一个链表的剩余节点直接连接到链表后面, 注意处理进位.

代码

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
    flag := 0
    current1 := l1
    current2 := l2
    head := current1
    for current1.Next != nil && current2.Next != nil{
        current1.Val = current1.Val + current2.Val + flag
        if current1.Val >= 10{
            current1.Val -= 10
            flag = 1
        }else{
            flag = 0
        }
        current1 = current1.Next
        current2 = current2.Next
    }
    if current1.Next == nil && current2.Next == nil{
        current1.Val = current1.Val + current2.Val + flag
        if current1.Val >= 10{
            current1.Val -= 10
            current1.Next = &ListNode{1, nil}
        }
        return head
    }else if current1.Next == nil{
        current1.Val = current1.Val + current2.Val + flag
        if current1.Val >= 10{
            current1.Val -= 10
            flag = 1
        }else{
            flag = 0
        }
        current1.Next = current2.Next
    }else{
        current1.Val = current1.Val + current2.Val + flag
        if current1.Val >= 10{
            current1.Val -= 10
            flag = 1
        }else{
            flag = 0
        }
    }
    current1 = current1.Next
    for current1.Next != nil && flag == 1{
        current1.Val += flag
        if current1.Val >= 10{
            current1.Val -= 10
            flag = 1
        }else{
            flag = 0
        }
        current1 = current1.Next
    }
    if flag == 1{
        current1.Val += flag
        if current1.Val >= 10{
            current1.Val -= 10
            current1.Next = &ListNode{1,nil}
        }
    }
    return head
}
1 个赞

刷题佬!

2 个赞

From 算法 to 开发调优