2807. 在链表中插入最大公约数

2807. 在链表中插入最大公约数

解法一: 辗转相除法

go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func insertGreatestCommonDivisors(head *ListNode) *ListNode {
first := head
second := head.Next
for second != nil {
first.Next = &ListNode{
Val: gcd(first.Val, second.Val),
Next: second,
}
first, second = second, second.Next
}
return head
}

func gcd(num1, num2 int) int {
for num2 != 0 {
num1, num2 = num2, num1 % num2
}
return num1
}
作者

wuhunyu

发布于

2024-01-06

更新于

2024-01-06

许可协议