We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
2 parents b308101 + 81bbb01 commit bfe5ec3Copy full SHA for bfe5ec3
Program to toggle Kth bit of a number.cpp
@@ -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