-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcheck_ith_bit_set.cpp
50 lines (37 loc) · 951 Bytes
/
check_ith_bit_set.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
/****************************************************************************
File name: check_ith_bit_set.cpp
Author: babajr
*****************************************************************************/
/*
Check if the ith bit is set in the binary form of the given number.
Input: N = 4 (0100), i = 0
Output: 0 -->
*/
#include <iostream>
#include <algorithm>
#include <cassert>
using namespace std;
/*Approach 1 */
int checkSetBit(int num, int i)
{
// (1 << i) --> 2 ^ i.
// We are shifting 1 by i and checking whether ith bit in num is set or not.
if(num & (1 << i))
return 1;
else
return -1;
}
int main(void)
{
int num, checkBit, i;
cout<<"Please Enter the number: ";
cin>>num;
cout<<"Please Enter the bit to check: ";
cin>>i;
checkBit = checkSetBit(num, i);
if(checkBit == 1)
cout<<i<<"th bit is set";
else
cout<<i<<"th bit is not set";
return 0;
}