Thursday, December 24, 2020

Given an integer check if it is a power of four

Problem: Given an integer num, return true if it is a power of four. Otherwise, return false.

Example:

Input: num = 64
Output: true


Approach: Here are the points which we need to focus:

  1. if input number is 0, it is not power of 4 (obviously).
  2. Any number which is a power of 4 will definitely be a power of 2.
  3. We know that num is power of 2 if if num & (nums - 1) is 0. 
  4. Every number which is power of 2, is a power of 4 if num - 1 is divisible by 3. You can see this by examples or you can look at the proof by induction here
If you understood the above points. Solution can be easily understood by just looking at the implementation.

Implementation:

        public bool IsPowerOfFour(int num)

        {

            return num > 0 && (num & (num - 1)) == 0 && (num - 1) % 3 == 0;

        }


Complexity: O(1)

No comments:

Post a Comment