Power of Two

Problem

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

Solution

Regular Iterative Solution: O(n) time and O(1) space

public class Solution {
    public boolean isPowerOfTwo(int n) {
        if (n < 1) return false;
        while (n % 2 == 0) n /= 2;
        return n == 1;
    }
}

Use of Integer.MAX_VALUE Solution: 2^30 O(1) time and O(1) space

public class Solution {
    public boolean isPowerOfTwo(int n) {
        return n > 0 && Math.pow(2, 30) % n == 0;
    }
}

Analysis

Please Refer to the analysis in Power of Three

results matching ""

    No results matching ""