Home » leet code » Leetcode 342. Power of Four (Easy)

Leetcode 342. Power of Four (Easy)

LeetCode 342. Power of Four :Hey there, coding enthusiasts! Welcome back to another exciting coding session. Today’s problem is a treat—literally! We’re going to solve the “Power of Four” or “LeetCode 342. Method we are using are Mathematical approach and Bit Manipulation.

Approach : Mathematical

  1. First Step to check negative : The code first checks if the input number n is less than or equal to zero. If n is non-positive, the function returns false, as power of four numbers are always positive.
  2. Logarithmic Calculation (check it four or not): It calculates the logarithm of n to the base 4 using the log function from the C++ math library. This is done to determine if n is a power of four.
  3. Modulo Operation(checking fractional part of Number): It then uses the fmod function to check if the result of the logarithmic calculation has a fractional part. If the result has no fractional part (i.e., it equals zero), the function returns true, indicating that n is a power of four.
LineExplanationnxfmod(x, 1.0)Output
1Check if n <= 0.16
2Calculate x as log(n) / log(4).162.0
3Check if the fractional part of x is equal to 0.162.00.0true
Dry and Run math Approach

Codes : Mathematical Approach – Leetcde 342 Power of 4

C++

class Solution {
public:
    bool isPowerOfFour(int n) {
      if (n <= 0) return false;
    double x = log(n) / log(4);
    return fmod(x, 1.0) == 0;  
    }
};

Java : Leet code-342 Math Approach

class Solution {
    public boolean isPowerOfFour(int n) {
      if (n <= 0) return false;
        double x = Math.log(n) / Math.log(4);
        return x % 1 == 0;  
    }
}

Python : Leet Code Power of Four Math Approach

class Solution(object):
    def isPowerOfFour(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n <= 0:
            return False
        x = math.log(n, 4)
        return x.is_integer()
        

JavaScript : Leet code .342 power of four Math Approach

/**
 * @param {number} n
 * @return {boolean}
 */
var isPowerOfFour = function(n) {
    if (n <= 0) return false;
    const x = Math.log(n) / Math.log(4);
    return Number.isInteger(x);
};

Rust: Math Easy Approach

impl Solution {
    pub fn is_power_of_four(n: i32) -> bool {
        if n <= 0 {
        return false;
    }
    
    let x = (n as f64).log(4.0);
    (x % 1.0).abs() < f64::EPSILON
    }
}

GO Lang : Simple Mathematical Approach

func isPowerOfFour(n int) bool {
    if n <= 0 {
		return false
	}
	x := math.Log(float64(n)) / math.Log(4)
	return math.Mod(x, 1) == 0
}

Dart : Leet code 342

class Solution {
  bool isPowerOfFour(int n) {
if (n <= 0) return false;
  double x = log(n) / log(4);
  return x % 1 == 0;
  }
}

Approach : Bit Manupulation (1 Line Code)

  1. Positive Check: It first checks if the input number is greater than 0. This ensures we are only dealing with positive numbers, as negative numbers can’t be powers of four.
  2. Power of Two Check: It then uses bitwise operations to check if the number is a power of two. (num & (num - 1)) == 0 checks if it’s a power of two, as powers of two have only one bit set.
  3. Power of Four Check: The code further checks if the number satisfies the pattern of a power of four by using the bitwise AND operation with the hexadecimal value 0x55555555. If this check is true, it means the number is a power of four.

input n = 16:

ConditionExplanationResult
num > 0Is n greater than 0?true
num & (num – 1) == 0Is n a power of 2? (16 is 2^4)true
num & 0x55555555 == numIs the ‘1’ bit in n at an even position?true
Dry and Run of Bit Manupulation

Since all three conditions are true, the function returns true for the input n = 16.

Bit Manupulation Approach – Power of four (1 line code)

C++: Leet Code 342 Bit Manupulation Approach

class Solution {
public:
    bool isPowerOfFour(int num) {
     return (num > 0) && ((num & (num - 1)) == 0) && ((num & 0x55555555) == num);
    }
};

Java: Power of Four Bit Manupulation

class Solution {
    public static boolean isPowerOfFour(int num) {
        return (num > 0) && ((num & (num - 1)) == 0) && ((num & 0x55555555) == num);
    }
}

Python:Leetcode Power of Four Bit Manupulation

class Solution(object):
    def isPowerOfFour(self, num):
        """
        :type n: int
        :rtype: bool
        """
        return num > 0 and (num & (num - 1) == 0) and (num & 0x55555555 == num)

JavaScript: Leet Code 342 . Bit Manupulation

/**
 * @param {number} n
 * @return {boolean}
 */
var isPowerOfFour = function(num) {
    return num > 0 && (num & (num - 1)) === 0 && (num & 0x55555555) === num;
};

Dart: Bit Manupulation Power of Four Bit Manupulation

class Solution {
  bool isPowerOfFour(int num) {
  return num > 0 && (num & (num - 1) == 0) && (num & 0x55555555 == num);
}
}

Go:Power of Four Easy Bit Manupulation

func isPowerOfFour(num int) bool {
return num > 0 && (num & (num - 1) == 0) && (num & 0x55555555 == num)
}

Rust:Efficient Bitwise Manupulation

impl Solution {
    pub fn is_power_of_four(num: i32) -> bool {
      num > 0 && (num & (num - 1) == 0) && (num & 0x55555555 == num)
    }
}
List of Some important Leet code Questions:

Leave a Comment

Your email address will not be published. Required fields are marked *