AC Java Solution using log with explanation

  • 0

    The idea is to find the exponent of the given number using the log method of the Math class. If the given number is a power of 4, a number calculated with the power of 4 to this exponent should be equal to the given number.

    public class Solution {
        public boolean isPowerOfFour(int num) {
            if(num == 0)
                return false;
            // Finding the closest (floor) exponent of the number by calculating its log with the base 4
            int exponent = (int)(Math.log(num)/Math.log(4));
            // Finding the number with 4 to the power of the calculated exponent
            int result = (int) Math.pow(4, exponent);
            return num == result; // If the given number and the result match, it means the given number is a power of 4.

Log in to reply

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