mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-05 00:25:22 +08:00
规范格式
This commit is contained in:
18
leetcode/0342.Power-of-Four/342. Power of Four.go
Normal file
18
leetcode/0342.Power-of-Four/342. Power of Four.go
Normal file
@ -0,0 +1,18 @@
|
||||
package leetcode
|
||||
|
||||
// 解法一 数论
|
||||
func isPowerOfFour(num int) bool {
|
||||
return num > 0 && (num&(num-1)) == 0 && (num-1)%3 == 0
|
||||
}
|
||||
|
||||
// 解法二 循环
|
||||
func isPowerOfFour1(num int) bool {
|
||||
for num >= 4 {
|
||||
if num%4 == 0 {
|
||||
num = num / 4
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return num == 1
|
||||
}
|
47
leetcode/0342.Power-of-Four/342. Power of Four_test.go
Normal file
47
leetcode/0342.Power-of-Four/342. Power of Four_test.go
Normal file
@ -0,0 +1,47 @@
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type question342 struct {
|
||||
para342
|
||||
ans342
|
||||
}
|
||||
|
||||
// para 是参数
|
||||
// one 代表第一个参数
|
||||
type para342 struct {
|
||||
one int
|
||||
}
|
||||
|
||||
// ans 是答案
|
||||
// one 代表第一个答案
|
||||
type ans342 struct {
|
||||
one bool
|
||||
}
|
||||
|
||||
func Test_Problem342(t *testing.T) {
|
||||
|
||||
qs := []question342{
|
||||
|
||||
question342{
|
||||
para342{16},
|
||||
ans342{true},
|
||||
},
|
||||
|
||||
question342{
|
||||
para342{5},
|
||||
ans342{false},
|
||||
},
|
||||
}
|
||||
|
||||
fmt.Printf("------------------------Leetcode Problem 342------------------------\n")
|
||||
|
||||
for _, q := range qs {
|
||||
_, p := q.ans342, q.para342
|
||||
fmt.Printf("【input】:%v 【output】:%v\n", p, isPowerOfFour(p.one))
|
||||
}
|
||||
fmt.Printf("\n\n\n")
|
||||
}
|
29
leetcode/0342.Power-of-Four/README.md
Executable file
29
leetcode/0342.Power-of-Four/README.md
Executable file
@ -0,0 +1,29 @@
|
||||
# [342. Power of Four](https://leetcode.com/problems/power-of-four/)
|
||||
|
||||
|
||||
## 题目
|
||||
|
||||
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
|
||||
|
||||
**Example 1:**
|
||||
|
||||
Input: 16
|
||||
Output: true
|
||||
|
||||
**Example 2:**
|
||||
|
||||
Input: 5
|
||||
Output: false
|
||||
|
||||
**Follow up**: Could you solve it without loops/recursion?
|
||||
|
||||
## 题目大意
|
||||
|
||||
给定一个整数 (32 位有符号整数),请编写一个函数来判断它是否是 4 的幂次方。
|
||||
|
||||
|
||||
## 解题思路
|
||||
|
||||
- 判断一个数是不是 4 的 n 次方。
|
||||
- 这一题最简单的思路是循环,可以通过。但是题目要求不循环就要判断,这就需要用到数论的知识了。
|
||||
- 证明 `(4^n - 1) % 3 == 0`,(1) `4^n - 1 = (2^n + 1) * (2^n - 1)`(2) 在任何连续的 3 个数中 `(2^n-1)`,`(2^n)`,`(2^n+1)`,一定有一个数是 3 的倍数。`(2^n)` 肯定不是 3 的倍数,那么 `(2^n-1)` 或者 `(2^n+1)` 中一定有一个是 3 的倍数。所以 `4^n-1` 一定是 3 的倍数。
|
Reference in New Issue
Block a user