Skip to content

Commit

Permalink
Create Program to toggle Kth bit of a number.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
MonalikaKapoor authored May 26, 2021
1 parent 3a2c6c7 commit 81bbb01
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions Program to toggle Kth bit of a number.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#include <iostream>
using namespace std;

// K starts from 1
// left shift 1 K-1 times and xor with number n
// 1<<K-1 generates a mask in which only Kth bit is set.

int ToggleKthBit(int n,int K)
{
return n ^ (1 << (K-1)); //toggled number
}

//driver program to check the code
int main()
{
int num,k;

cout<<"Enter number: ";
cin>>num;
cout<<"Enter bit to toggle (value of k): ";
cin>>k;

cout<<"Enter number: "<<num<<endl;
cout<<"Enter k: "<<k<<endl;

cout<<"original number before toggling: "<<num<<endl;

int new_number= ToggleKthBit(num,k);

cout<<"new number after toggling: "<<new_number<<endl;

return 0;
}

0 comments on commit 81bbb01

Please sign in to comment.