Finding a number which is a power of 2in a single step

How to find whether the given number is a power of 2 in single step (without using loops)?

Questions by rabia.sultana14

Showing Answers 1 - 4 of 4 Answers

reshmi_G

  • Jul 21st, 2011
 

Powers of 2 will have msb as 1 and all other bits as 0. This can be checked by left-shifting the number by 1 and checking if the result is 0 .

if((b<<1)==0)
"power of two"

  Was this answer useful?  Yes

Revathy

  • Aug 10th, 2011
 

Let us consider the binary numbers

ex:let n=8 let n=6

1000 0110
n-1=7 n-1=5

0111 0101

n&(n-1) n&(n-1)

1000 0110
0111 0101

0000 0100

with this example we can infer that for the number which is power of two,by taking its preceding number (i.e..,n-1) and performing &(and) operation we get zero.and for numbers which are not,if we perform the same operation we get non-zero value :)

Code
  1. #include<stdio.h>

  2. #include<conio.h>

  3. "enter the number");

  4.   scanf("%d""the number is power of two""it is not power of two");

  5. getch();

  6. }

  Was this answer useful?  Yes

sreethu

  • Aug 10th, 2011
 

This is based on binary numbers

Code
  1. #include<stdio.h>

  2. #include<conio.h>

  3. "enter the number");

  4.   scanf("%d""the number is power of two""it is not power of two");

  5. getch();

  6. }

  Was this answer useful?  Yes

Surender Reddy G

  • Jun 2nd, 2015
 

Code
  1. span style="color: #ff0000;">" x is not the power of 2""x is power of 2");

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions