• Status: Solved
• Priority: Medium
• Security: Public
• Views: 240

# Simplest code for checking if a number is 2 to the power n?

Hello,
I am new to C language. I just know printf and scanf. I need some code very urgently. Can you give me simplese code possible (Not more than 4 lines), to check whether a number is 2 to the power n or not.
Eg :
For the numbers 2, 4, 128 it should return 1;

MMT33
0
mmt33
1 Solution

Commented:
It is really simple. If you know bitwise operators, you have one line solution. As you are newbie, you can learn it later.

Suppose n is the variable which contains the number,,,,

if (( n & (n-1)) == 0)
{
printf("It is in the form of 2 to the power of n\r\n");
return(1);
else
return(0);
}

This works perfectly,

Sreenath
0

Author Commented:
That's too good. I  accept this answer and thanks to you sreenathk

mmt33
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.