-
Notifications
You must be signed in to change notification settings - Fork 21
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #80 from MonalikaKapoor/Toggle-Kth-Bit
Added the code to toggle Kth bit of a number.cpp
- Loading branch information
Showing
1 changed file
with
33 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |