Two 1 line Java solutions


  • 2
    R

    Solution 1: convert it into radix 4 number, and check if it is in format "1", "10", "100", "1000" ... etc.

    public class Solution {
        public boolean isPowerOfFour(int num) {
            return Integer.toString(num, 4).matches("10*");
        }
    }
    

    Time is O( log n) due to toString and matches both cost O( log n).

    Solution 2: check if its binary has only ONE "1" bit and EVEN number of trailing zeros. Theory is similar to above, but no need of conversion into binary.

    public class Solution {
        public boolean isPowerOfFour(int num) {
            return (Integer.bitCount(num) == 1) && ((Integer.numberOfTrailingZeros(num) % 2) == 0);
        }
    }
    

    The time is also O( log n), because bitCount and numberOfTrailingZeros both cost O( log n).


  • 0
    H

    very nice! also comments on programs (30 char limit... lol)


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.