It is very much easy to check the power of 2. If you observe the pattern for the different numbers.
For example:
3 = 11
4 = 100
7 = 111
8 = 1000
15 = 1111
16 = 10000
31 = 11111
32 = 100000
Observe that both numbers carefully. You can see if you do anding of both the numbers then result will be zero.
Example 3 & 4 = 0.
#include "stdafx.h"
#include "stdio.h"
#include "conio.h"
#include "string.h"
#include "stdlib.h"
int _tmain(int argc, _TCHAR* argv[])
{
int chPow2 = 30;
if((chPow2 & (chPow2 - 1)) == 0)
printf("Number: %d is power of 2", chPow2);
else
printf("Number: %d is not power of 2", chPow2);
getch();
return 0;
}
For example:
3 = 11
4 = 100
7 = 111
8 = 1000
15 = 1111
16 = 10000
31 = 11111
32 = 100000
Observe that both numbers carefully. You can see if you do anding of both the numbers then result will be zero.
Example 3 & 4 = 0.
#include "stdafx.h"
#include "stdio.h"
#include "conio.h"
#include "string.h"
#include "stdlib.h"
int _tmain(int argc, _TCHAR* argv[])
{
int chPow2 = 30;
if((chPow2 & (chPow2 - 1)) == 0)
printf("Number: %d is power of 2", chPow2);
else
printf("Number: %d is not power of 2", chPow2);
getch();
return 0;
}
0 comments :
Post a Comment