A PHP Error was encountered

Severity: 8192

Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated

Filename: libraries/Filtered_db.php

Line Number: 23

C++ program to clear Kth bit of a number
Q:

C++ program to clear Kth bit of a number

0

To write a C++ program to clear Kth bit of a number.

Constraints: 1<=n<=100

Example:

    Input:
    Enter number: 11
    Enter k: 4

    Output:
    original number before clearing: 11
    new number after clearing: 3

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Algorithm:

  1. Input the number and Kth bit to be cleared.
  2. Left shift 1 - (K-1) times to create a mask where only Kth bit is set.
  3. Take bitwise complement of the mask.
  4. Perform bitwise AND of original number with this mask to clear the Kth bit.
  5. 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 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now