Check if Given Number is power of 2.

Objective: Given a number, write a program to find if number is power of two.

Example:

N = 5
Output: false.

N = 8
Output: true (23)

N = 512
Output: true (29)

Approach:

This problem can be solved in multiple ways; we will discuss three solutions here.

  • Log2 Method
  • Check the Remainder
  • Convert number to bits

Log2 Method:

Get the log of the number with base 2 and if outcome is integer then number is power of 2.
Code:

Output:

Given number 6 is not power of 2
Given number 8 is power of 2
Given number 24 is not power of 2
Given number 512 is power of 2

Method – Check the Remainder:
Keep dividing the number by 2 till n =1, and during this iteration if any time number%2 is non zero then number is not power of 2 else the number is power of 2.

Code

Output:

Given number 6 is not power of 2
Given number 8 is power of 2
Given number 24 is not power of 2
Given number 512 is power of 2

Method – Bit Manipulation

  • Every number which is a power of 2 has only one bit set (4 = 1 0 0, 8 = 1 0 0 0, 16 = 1 0 0 0 0),
  • Convert the given number into binary and count the number of set bits, if count > 1 then number is not power of 2 else the number is power of 2.

Code:

Output:

Given number 6 is not power of 2
Given number 8 is power of 2
Given number 24 is not power of 2
Given number 512 is power of 2

Reference: Here

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

%d bloggers like this: