mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-29 23:23:42 +08:00
70 lines
1.6 KiB
Markdown
Executable File
70 lines
1.6 KiB
Markdown
Executable File
# [231. Power of Two](https://leetcode.com/problems/power-of-two/)
|
|
|
|
## 题目
|
|
|
|
Given an integer, write a function to determine if it is a power of two.
|
|
|
|
**Example 1**:
|
|
|
|
Input: 1
|
|
Output: true
|
|
Explanation: 2^0 = 1
|
|
|
|
**Example 2**:
|
|
|
|
Input: 16
|
|
Output: true
|
|
Explanation: 2^4 = 16
|
|
|
|
**Example 3**:
|
|
|
|
Input: 218
|
|
Output: false
|
|
|
|
## 题目大意
|
|
|
|
给定一个整数,编写一个函数来判断它是否是 2 的幂次方。
|
|
|
|
|
|
## 解题思路
|
|
|
|
- 判断一个数是不是 2 的 n 次方。
|
|
- 这一题最简单的思路是循环,可以通过。但是题目要求不循环就要判断,这就需要用到数论的知识了。这一题和第 326 题是一样的思路。
|
|
|
|
|
|
## 代码
|
|
|
|
```go
|
|
|
|
package leetcode
|
|
|
|
// 解法一 二进制位操作法
|
|
func isPowerOfTwo(num int) bool {
|
|
return (num > 0 && ((num & (num - 1)) == 0))
|
|
}
|
|
|
|
// 解法二 数论
|
|
func isPowerOfTwo1(num int) bool {
|
|
return num > 0 && (1073741824%num == 0)
|
|
}
|
|
|
|
// 解法三 打表法
|
|
func isPowerOfTwo2(num int) bool {
|
|
allPowerOfTwoMap := map[int]int{1: 1, 2: 2, 4: 4, 8: 8, 16: 16, 32: 32, 64: 64, 128: 128, 256: 256, 512: 512, 1024: 1024, 2048: 2048, 4096: 4096, 8192: 8192, 16384: 16384, 32768: 32768, 65536: 65536, 131072: 131072, 262144: 262144, 524288: 524288, 1048576: 1048576, 2097152: 2097152, 4194304: 4194304, 8388608: 8388608, 16777216: 16777216, 33554432: 33554432, 67108864: 67108864, 134217728: 134217728, 268435456: 268435456, 536870912: 536870912, 1073741824: 1073741824}
|
|
_, ok := allPowerOfTwoMap[num]
|
|
return ok
|
|
}
|
|
|
|
// 解法四 循环
|
|
func isPowerOfTwo3(num int) bool {
|
|
for num >= 2 {
|
|
if num%2 == 0 {
|
|
num = num / 2
|
|
} else {
|
|
return false
|
|
}
|
|
}
|
|
return num == 1
|
|
}
|
|
|
|
``` |