Contents

231. Power of Two

Problem

Given an integer, write a function to determine if it is a power of two.

example 1

1
2
3
Input: 1
Output: true 
Explanation: 2^0 = 1

example 2

1
2
3
Input: 16
Output: true
Explanation: 2^4 = 16

example 3

1
2
Input: 218
Output: false

Solution

Recursion

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
func isPowerOfTwo(n int) bool {
    if n<=0 {
        return false
    }
    
    if n == 1 {
        return true
    }
    if n%2 == 1{
        return false
    }
    return isPowerOfTwo(n>>1)
}

For

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
func isPowerOfTwo(n int) bool {
    if n<=0 {
        return false
    }
    
    for ;n >1;n=n>>1 {
        if n%2 == 1 {
            return false
        }
    }
    return true
}