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 - 10 of 10 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. int power_of_two(int);

  4. void main()

  5. {

  6.   int n;

  7.   printf("enter the number");

  8.   scanf("%d",&n);

  9.   power_of_two(n);

  10. }

  11. int power_of_two(int n)

  12. {

  13.  if((n&(n-1))==0)

  14.     printf("the number is power of two");

  15.  else

  16.     printf("it is not power of two");

  17. getch();

  18. }

  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. int power_of_two(int);

  4. void main()

  5. {

  6.   int n;

  7.   printf("enter the number");

  8.   scanf("%d",&n);

  9.   power_of_two(n);

  10. }

  11. int power_of_two(int n)

  12. {

  13.  if((n&(n-1))==0)

  14.     printf("the number is power of two");

  15.  else

  16.     printf("it is not power of two");

  17. getch();

  18. }

  Was this answer useful?  Yes

Surender Reddy G

  • Jun 2nd, 2015
 

Code
  1. int x=64;

  2. if(x&&(x&(x-1))) printf(" x is not the power of 2");

  3. else printf("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