Q:

C++ program to toggle Kth bit of a number

0

Program to toggle the Kth bit of a number in C++: Here we are going to use bitwise operators to toggle Kth bit in the binary representation of a given number.

Problem Statement: To write a C++ program to toggle Kth bit of a number.

Constraints: 1<=n<=100

Example:

    
    Input:
    Enter number: 5
    Enter k: 2

    Output:
    original number before toggling: 5
    new number after toggling: 7

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 toggled.
  2. Left shift 1 - (K-1) times to create a mask where only Kth bit is set.
  3. Perform bitwise XOR with this mask to toggle the Kth bit.
  4. Output the result after XOR in decimal form.

C++ Implementation:

#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;
}

Output

Enter number: 5
Enter bit to toggle (value of k): 2
Enter number: 5
Enter k: 2
original number before toggling: 5
new number after toggling: 7

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