Left shift 1 - (K-1) times to create a mask where only Kth bit is set.
Take bitwise complement of the mask.
Perform bitwise AND of original number with this mask to clear the Kth bit.
Output the result after bitwise AND in decimal form.
C++ Implementation:
#include <iostream>
using namespace std;
int clearKthBit(int n,int k)
{
// left shift 1 , (k-1) times to get a mask
// in which only kth bit is set
int m=1<<(k-1);
// bitwise complement of mask
m=~(m);
// new number after clearing kth bit
return (n&m);
}
//driver program to check the code
int main()
{
int num,k;
cout<<"Enter number: ";
cin>>num;
cout<<"Enter k: ";
cin>>k;
cout<<"original number before clearing: "<<num<<endl;
int new_number= clearKthBit(num,k);
cout<<"new number after clearing: "<<new_number<<endl;
return 0;
}
Output
Enter number: 11
Enter k: 4
original number before clearing: 11
new number after clearing: 3
Algorithm:
C++ Implementation:
Output
need an explanation for this answer? contact us directly to get an explanation for this answer