-
Notifications
You must be signed in to change notification settings - Fork 2
/
is_power_of_2.cpp
57 lines (43 loc) · 1.02 KB
/
is_power_of_2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/****************************************************************************
File name: is_power_of_2.cpp
Author: babajr
*****************************************************************************/
/*
Check if a given number is a power of 2. On success return True(1) else, return False(-1)
Input: 4
Output: True (1)
*/
#include <iostream>
#include <algorithm>
#include <cassert>
using namespace std;
/* Approach 1: General way. */
/*
int isPowerOfTwo(int num)
{
if(num == 0) // special case
return -1;
else
{
while(num % 2 == 0)
num /= 2;
return (num == 1);
}
}
*/
/*Approach 2: Using bitwise operator. */
int isPowerOfTwo(int num)
{
return (num && !(num & (num - 1))); // num will check if num == 0 and !(num & (num - 1)) will check if it's power of 2.
}
int main(void)
{
int num;
cout<<"Please Enter the number: ";
cin>>num;
if(isPowerOfTwo(num))
cout<<num<<" is power of 2\n";
else
cout<<num<<" is not power of 2\n";
return 0;
}