mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-30 23:52:03 +08:00
77 lines
1.6 KiB
Markdown
Executable File
77 lines
1.6 KiB
Markdown
Executable File
# [326. Power of Three](https://leetcode.com/problems/power-of-three/)
|
|
|
|
|
|
## 题目
|
|
|
|
Given an integer, write a function to determine if it is a power of three.
|
|
|
|
**Example 1**:
|
|
|
|
Input: 27
|
|
Output: true
|
|
|
|
**Example 2**:
|
|
|
|
Input: 0
|
|
Output: false
|
|
|
|
**Example 3**:
|
|
|
|
Input: 9
|
|
Output: true
|
|
|
|
**Example 4**:
|
|
|
|
Input: 45
|
|
Output: false
|
|
|
|
**Follow up**:
|
|
|
|
Could you do it without using any loop / recursion?
|
|
|
|
|
|
## 题目大意
|
|
|
|
给定一个整数,写一个函数来判断它是否是 3 的幂次方。
|
|
|
|
|
|
## 解题思路
|
|
|
|
- 判断一个数是不是 3 的 n 次方。
|
|
- 这一题最简单的思路是循环,可以通过。但是题目要求不循环就要判断,这就需要用到数论的知识了。由于 3^20 超过了 int 的范围了,所以 3^19 次方就是 int 类型中最大的值。这一题和第 231 题是一样的思路。
|
|
|
|
|
|
|
|
## 代码
|
|
|
|
```go
|
|
|
|
package leetcode
|
|
|
|
// 解法一 数论
|
|
func isPowerOfThree(n int) bool {
|
|
// 1162261467 is 3^19, 3^20 is bigger than int
|
|
return n > 0 && (1162261467%n == 0)
|
|
}
|
|
|
|
// 解法二 打表法
|
|
func isPowerOfThree1(n int) bool {
|
|
// 1162261467 is 3^19, 3^20 is bigger than int
|
|
allPowerOfThreeMap := map[int]int{1: 1, 3: 3, 9: 9, 27: 27, 81: 81, 243: 243, 729: 729, 2187: 2187, 6561: 6561, 19683: 19683, 59049: 59049, 177147: 177147, 531441: 531441, 1594323: 1594323, 4782969: 4782969, 14348907: 14348907, 43046721: 43046721, 129140163: 129140163, 387420489: 387420489, 1162261467: 1162261467}
|
|
_, ok := allPowerOfThreeMap[n]
|
|
return ok
|
|
}
|
|
|
|
// 解法三 循环
|
|
func isPowerOfThree2(num int) bool {
|
|
for num >= 3 {
|
|
if num%3 == 0 {
|
|
num = num / 3
|
|
} else {
|
|
return false
|
|
}
|
|
}
|
|
return num == 1
|
|
}
|
|
|
|
``` |