Open In App

Toggling k-th bit of a number

Last Updated : 13 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

For a given number n, if k-th bit is 0, then toggle it to 1 and if it is 1 then, toggle it to 0.


Examples :  

Input : n = 6, k = 1
Output : 7
6 is represented as 110 in binary and has its first bit 0, so toggling it will result in 111 i.e. 7.

Input : n = 2, k = 3
Output : 6
2 is represented as 010 in binary and has its 3rd bit 0, so toggling it will result in 110 i.e. 6.

Input : n = 75, k = 4
Output : 67
75 is represented as 1001011 in binary and has its 4th bit 1, so toggling it will result in 1000011 i.e. 67.

 Below are simple steps to find the value of k-th bit  

1) Left shift given number 1 by k-1 to create a number that has only set bit as k-th bit. mask = 1 << (k-1) 2) Return bitwise XOR of temp and n. Since mask has only k-th bit set, doing XOR would toggle only this bit.

Example : 

n = 75 and k = 4 temp = 1 << (k-1) = 1 << 3 = 8 Binary Representation of temp = 0..00001000 Binary Representation of n = 0..01001011 Bitwise XOR of two numbers = 0..01000011
 

C++
// CPP program to toggle k-th bit of n
#include<iostream>
using namespace std;

int toggleKthBit(int n, int k)
{
    return (n ^ (1 << (k-1)));
}

// Driver code
int main()
{
    int n = 5, k = 1;
    cout << toggleKthBit(n , k);
    return 0;
}
Java
 
// Java program to toggle
// k-th bit of a number

class Toggle
{
    static int toggleKthBit(int n, int k)
    {
        return (n ^ (1 << (k-1)));
    }
    
    // main function 
    public static void main (String[] args) 
    {   
        int n = 5, k = 1;
        System.out.println(toggleKthBit(n , k));
    }
}
Python3
# Python3 code to toggle k-th bit of n

def toggleKthBit(n, k):
    return (n ^ (1 << (k-1)))
    
# Driver code
n = 5
k = 1
print( toggleKthBit(n , k))

# This code is contributed by "Sharad_Bhardwaj".
C#
// C# program to toggle
// k-th bit of a number
using System;

class GFG {
    
    static int toggleKthBit(int n, int k)
    {
        return (n ^ (1 << (k-1)));
    }
     
    // main function 
    public static void Main() 
    {   
        int n = 5, k = 1;
        
        Console.WriteLine(toggleKthBit(n , k));
    }
}

//This code is contributed by Anant Agarwal.
JavaScript
<script>

    // Javascript program to toggle
    // k-th bit of a number
    
    function toggleKthBit(n, k)
    {
        return (n ^ (1 << (k-1)));
    }
    
    let n = 5, k = 1;
          
      document.write(toggleKthBit(n , k));
    
</script>
PHP
<?php
// Php program to toggle k-th bit of n

function toggleKthBit($n, $k)
{
    return ($n ^ (1 << ($k - 1)));
}

// Driver code
$n = 5;
$k = 1;
echo toggleKthBit($n, $k);

// This code is contributed by Ajit
?>

Output :  

4

Time Complexity : O(1)
Space Complexity : O(1)
 


Next Article
Article Tags :
Practice Tags :

Similar Reads