Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added the code to toggle Kth bit of a number.cpp #80

Merged
merged 1 commit into from
Nov 17, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
}