Skip to content

Commit bfe5ec3

Browse files
authored
Merge pull request #80 from MonalikaKapoor/Toggle-Kth-Bit
Added the code to toggle Kth bit of a number.cpp
2 parents b308101 + 81bbb01 commit bfe5ec3

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
#include <iostream>
2+
using namespace std;
3+
4+
// K starts from 1
5+
// left shift 1 K-1 times and xor with number n
6+
// 1<<K-1 generates a mask in which only Kth bit is set.
7+
8+
int ToggleKthBit(int n,int K)
9+
{
10+
return n ^ (1 << (K-1)); //toggled number
11+
}
12+
13+
//driver program to check the code
14+
int main()
15+
{
16+
int num,k;
17+
18+
cout<<"Enter number: ";
19+
cin>>num;
20+
cout<<"Enter bit to toggle (value of k): ";
21+
cin>>k;
22+
23+
cout<<"Enter number: "<<num<<endl;
24+
cout<<"Enter k: "<<k<<endl;
25+
26+
cout<<"original number before toggling: "<<num<<endl;
27+
28+
int new_number= ToggleKthBit(num,k);
29+
30+
cout<<"new number after toggling: "<<new_number<<endl;
31+
32+
return 0;
33+
}

0 commit comments

Comments
 (0)