š§© Problem Statement
Given an integer n
, write a function to determine if it is a power of two.
To be a power of two, the number n
must be a positive integer, and there must exist an integer x
such that:
n=2xn = 2^xn=2xYou need to implement the following function:
go
func isPowerOfTwo(n int) bool
š Example
go
Input: n = 1
Output: true
Explanation: 2^0 = 1
Input: n = 16
Output: true
Explanation: 2^4 = 16
Input: n = 3
Output: false
Explanation: 3 is not a power of two.
š Explanation:
- Example 1:
- The number
1
is a power of two because 20=12^0 = 120=1.
- Therefore, the answer is
true
.
- Example 2:
- The number
16
is a power of two because 24=162^4 = 1624=16.
- Therefore, the answer is
true
.
- Example 3:
- The number
3
is not a power of two.
- Therefore, the answer is
false
.
š§ Approach
To determine if a number n
is a power of two:
- Bit Manipulation:
- A number
n
that is a power of two has exactly one 1
bit in its binary representation.
- This can be verified by the following trick:
- If
n
is a power of two, then n & (n - 1)
will be 0
. This is because:
- For example, if
n = 8
(binary: 1000
), n - 1 = 7
(binary: 0111
), and n & (n - 1) = 1000 & 0111 = 0
.
- However, this only works for positive integers. Therefore, we must also check that
n > 0
.
- Condition:
- The number
n
is a power of two if:
- n>0and(n&(nā1))==0n > 0 \quad \text{and} \quad (n \& (n - 1)) == 0n>0and(n&(nā1))==0
ā
Go Implementation
go
package main
import "fmt"
// Function to check if a number is a power of two
func isPowerOfTwo(n int) bool {
// A number is a power of two if it's greater than 0 and (n & (n - 1)) is 0
return n > 0 && (n & (n - 1)) == 0
}
// Test the isPowerOfTwo function
func main() {
// Test case 1
fmt.Println(isPowerOfTwo(1)) // Output: true
// Test case 2
fmt.Println(isPowerOfTwo(16)) // Output: true
// Test case 3
fmt.Println(isPowerOfTwo(3)) // Output: false
// Test case 4
fmt.Println(isPowerOfTwo(0)) // Output: false
}
š¦ Example Usage
go
func main() {
// Test case 1: Output should be true
fmt.Println(isPowerOfTwo(1)) // Output: true
// Test case 2: Output should be true
fmt.Println(isPowerOfTwo(16)) // Output: true
// Test case 3: Output should be false
fmt.Println(isPowerOfTwo(3)) // Output: false
// Test case 4: Output should be false (since 0 is not a power of two)
fmt.Println(isPowerOfTwo(0)) // Output: false
}
ā±ļø Time & Space Complexity
- Time Complexity:
- O(1): The bitwise operations take constant time.
- Space Complexity:
- O(1): We use a constant amount of space, as we only need to store the result of the bitwise operation.
This solution checks if a number is a power of two efficiently using bit manipulation.