The Wayback Machine - https://web.archive.org/web/20240926134636/https://www.geeksforgeeks.org/toggling-k-th-bit-number/
Open In App

Toggling k-th bit of a number

Last Updated : 13 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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)
 



Similar Reads

Bit Toggling to Minimize Array Sum
Given an array arr[] consisting of positive integers of size N. the task is to minimize the overall sum of arr[] by toggling the unset bit (0 bit) of any element of the array for T times, where T is the total number of set bits over all the elements of arr[]. Note: In case of 32-bit integer overflow, return (overall Sum % 1e9 + 7). Examples: Input:
7 min read
Maximum Sum of Products of two arrays by toggling adjacent bits
Given an integer array arr1 and a binary array arr2 of same size, the task is to find the maximum possible sum of products of these arrays, i.e. (arr1[0] * arr2[0]) + (arr1[1] * arr2[1]) + ..... (arr1[N-1] * arr2[N-1]) obtained by toggling any 2 adjacent bits in the array arr2. This toggle can be done infinite number of times.Toggling of 2 adjacent
9 min read
Inserting M into N such that m starts at bit j and ends at bit i | Set-2
Given two 32-bit numbers, N and M, and two-bit positions, i and j. Write a method to insert M into N such that M starts at bit j and ends at bit i. You can assume that the bits j through i have enough space to fit all of M. Assuming index start from 0.Examples: a) N = 1024 (10000000000), M = 19 (10011), i = 2, j = 6 Output : 1100 (10001001100) b) N
10 min read
Count of 1-bit and 2-bit characters in the given binary string
Given two special characters, the first character can be represented by one bit which is 0 and the second character can be represented by two bits either 10 or 11. Now given a string represented by several bits. The task is to return the number of characters it represents. Note that the given string is always valid.Examples: Input: str = "11100" Ou
4 min read
Count bases which contains a set bit as the Most Significant Bit in the representation of N
Given a positive integer N, the task is to count the number of different bases in which, when N is represented, the most significant bit of N is a found to be a set bit. Examples: Input: N = 6Output: 4Explanation: The number 6 can be represented in 5 different bases, i.e. base 2, base 3, base 4, base 5, base 6. (6)10 in base 2: (110)2(6)10 in base
5 min read
Implementation of Bit Stuffing and Bit Destuffing
Bit Stuffing is a process of inserting an extra bit as 0, once the frame sequence encountered 5 consecutive 1's. Given an array, arr[] of size N consisting of 0's and 1's, the task is to return an array after the bit stuffing. Examples: Input: N = 6, arr[] = {1, 1, 1, 1, 1, 1}Output: 1111101Explanation: During the traversal of the array, 5 consecut
15 min read
Find the index at which bit must be set to maximise distance between next set bit
Given a binary array arr[]. The task is to find the position of any 0 in arr[] such that the distance between two set bits is maximized. Examples Input: arr = [1, 0, 0, 0, 1, 0, 1]Output: 2Explanation: Flip the bit at arr[2] Input: arr = [1, 0, 0, 0]Output: 3 Approach: The problem can be solved by finding the longest distance between adjacent set b
5 min read
Find X in range [1, N] of bit size A[i] such that X^2's bit size is not present in Array
Given an array A of N integers, where: Each element of array represents the bit size of an imaginary unsigned integer datatype.If ith imaginary datatype has a size of A[i] bits, then it can store integers from size 0 to 2A[i]-1. The task is to check if there exist some integer X, such that: X is in range 1 to NX can fit in a datatype of bit size A[
8 min read
Minimize bit flips such that each continuous segment of same bit has even length
Given a binary string S of even size that contains only 0s and 1s, the task is to find the minimum flips (that is 0 to 1 or 1 to 0) such that every contiguous subsegment that contains the same bit is of even size. Examples: Input: S = "1110011000 "Output: 3Explanation: Change S[2], S[5] and S[6] to '0'. After that S becomes "1100000000", it can be
8 min read
Find array elements with rightmost set bit at the position of the rightmost set bit in K
Given an array arr[] consisting of N and an integer K, the task is to print the elements of arr[] whose rightmost set bit is at the same position as the rightmost set bit in K. Examples: Input: arr[] = { 3, 4, 6, 7, 9, 12, 15 }, K = 7Output: { 3, 7, 9, 15 }Explanation:Binary representation of K (= 7) is 0111.Rightmost set bit in 7 is at position 1.
11 min read
Inserting m into n such that m starts at bit j and ends at bit i.
We are given two numbers n and m, and two-bit positions, i and j. Insert bits of m into n starting from j to i. We can assume that the bits j through i have enough space to fit all of m. That is, if m = 10011, you can assume that there are at least 5 bits between j and i. You would not, for example, have j = 3 and i = 2, because m could not fully f
8 min read
Toggle all the bits of a number except k-th bit.
Given a positive (or unsigned) integer n, write a function to toggle all the bits except k-th bit. Here value of k starts from 0 (zero) and from right. Examples: Input : n = 4294967295, k = 0 Output : 1 The number 4294967295 in 32 bits has all bits set. When we toggle all bits except last bit, we get 1. Input : n = 1, k = 1 Output : 4294967292 4294
4 min read
Remove one bit from a binary number to get maximum value
Given a binary number, the task is to remove exactly one bit from it such that, after it's removal, the resultant binary number is greatest from all the options.Examples: Input: 110 Output: 11 As 110 = 6 in decimal, the option is to remove either 0 or 1. So the possible combinations are 10, 11 The max number is 11 = 3 in decimal. Input:1001 Output:
4 min read
Check if a number is positive, negative or zero using bit operators
Given a number N, check if it is positive, negative or zero without using conditional statements.Examples: Input : 30 Output : 30 is positive Input : -20 Output : -20 is negative Input: 0 Output: 0 is zero The signed shift n&gt;&gt;31 converts every negative number into -1 and every other into 0. When we do a -n&gt;&gt;31, if it is a positive numbe
5 min read
For every set bit of a number toggle bits of other
Given two integer numbers, whenever the bits of the first number is set i.e. 1, toggle the bits of the second number leaving the rest bits of the second number unchanged. Examples : Input: 2 5 Output: 7 2 is represented as 10 in binary and 5 is represented as 101. Hence toggling the 2nd bit of 5 from right, thus the new number becomes 7 i.e. 111 In
3 min read
How to turn on a particular bit in a number?
Given a number n and a value k, turn on the k’th bit in n.Examples: Input: n = 4, k = 2 Output: 6 Input: n = 3, k = 3 Output: 7 Input: n = 64, k = 4 Output: 72 Input: n = 64, k = 5 Output: 80 The idea is to use bitwise &lt;&lt; and | operators. Using expression "(1 &lt;&lt; (k – 1))“, we get a number which has all bits unset, except the k’th bit. I
4 min read
Next greater number than N with exactly one bit different in binary representation of N
Given a number N. The task is to find the smallest number which is greater than N and has only one bit different in the binary representation of N. Note: Here N can be very large 10^9 &lt; N &lt; 10^15.Examples: Input : N = 11 Output : The next number is 15 The binary representation of 11 is 1011 So the smallest number greater than 11 with one bit
7 min read
Number of ways to swap two bit of s1 so that bitwise OR of s1 and s2 changes
Given two binary numbers strings [Tex]s1 [/Tex]and [Tex]s2 [/Tex]of length [Tex]N [/Tex]. Find the number of ways of swapping two bits in s1(only s1 not s2) so that bit-wise OR of these two numbers s1 and s2 are changed. Note: The length of both string must be equal, you can take leading zeros in case of different length. Example: Input: s1 = "0101
7 min read
Position of the K-th set bit in a number
Given two numbers N and K, The task is to find the index of the K-th set bit in the number from the right. Note: Indexing in the binary representation starts from 0 from the right. For example in the binary number "000011", the first set bit is at index 0 from the right, and the second set bit is at index 1 from the right.Examples: Input: N = 15, K
6 min read
Smallest number greater or equals to N such that it has no odd positioned bit set
Given an integer N, the task is to find the smallest integer X such that it has no odd position set and X ? N. Note: The positioning of bits is assumed from the right side and the first bit is assumed to be the 0th bit. Examples: Input: N = 9 Output: 16 16's binary representation is 10000, which has its 4th bit set which is the smallest number poss
12 min read
Number formed by the rightmost set bit in N
Given an integer N, the task is to find an integer M formed by taking the rightmost set bit in N i.e. the only set bit in M will be the rightmost set bit in N and the rest of the bits will be unset.Examples: Input: N = 7 Output: 1 7 = 111, the number formed by the last set bit is 001 i.e. 1.Input: N = 10 Output: 2 10 = 1010 -&gt; 0010 = 2Input: N =
4 min read
Program to clear K-th bit of a number N
Given a number N, the task is to clear the K-th bit of this number N. If K-th bit is 1, then clear it to 0 and if it is 0 then leave it unchanged.Examples: Input: N = 5, K = 1 Output: 4 5 is represented as 101 in binary and has its first bit 1, so clearing it will result in 100 i.e. 4. Input: N = 5, K = 2 Output: 5 5 is represented as 101 in binary
3 min read
Program to toggle K-th bit of a number N
Given a number N, the task is to clear the K-th bit of this number N. If K-th bit is 0, then set it to 1 and if it is 1 then set it to 0. Examples: Input: N = 5, K = 2 Output: 7 5 is represented as 101 in binary and has its second bit 0, so toggling it will result in 111 i.e. 7. Input: N = 5, K = 1 Output: 4 5 is represented as 101 in binary and ha
4 min read
Find most significant bit of a number X in base Y
Given two positive integers X and Y, the task is to find the MSB of X, in the given base Y.Examples: Input: X = 55, Y = 3 Output: 2 Explanation: 55 is 2001 in base 3 with first digit as 2.Input: X = 123, Y = 10 Output: 1 Explanation: 123 is 123 in base 10 with first digit 1. Approach: Let the task to find 1st digit of X = 1234 in base Y = 10, So to
4 min read
Number formed by flipping all bits to the left of rightmost set bit
Given an integer N, the task is to flip all the bits to the left of rightmost set bit and print the number generated. Examples: Input: N = 10 Output: 6 Explanation: 10 (1010 in binary) flipping all bits left to rightmost set bit (index 2) -&gt; 6 (0110 in binary) Input: N = 120 Output: 8 Explanation: 120 (1111000 in binary) flipping all bits left t
8 min read
Largest number M having bit count of N such that difference between their OR and XOR value is maximized
Given a natural number N, the task is to find the largest number M having the same length in binary representation as N such that the difference between N | M and N ^ M is maximum. Examples: Input: N = 6Output: 7Explanation: All number numbers having same length in binary representation as N are 4, 5, 6, 7.(6 | 4) - (6 ^ 4) = 4(6 | 5) - (6 ^ 5) = 4
6 min read
Smallest number exceeding N whose Kth bit is set
Given two integers N and K, the task is to find the smallest number greater than N whose Kth bit in its binary representation is set. Examples: Input: N = 15, K = 2Output: 20Explanation:The binary representation of (20)10 is (10100)2. The 2nd bit(0-based indexing) from left is set in (20)10. Therefore, 20 is the smallest number greater than 15 havi
12 min read
Find the maximum between N and the number formed by reversing 32-bit binary representation of N
Given a positive 32-bit integer N, the task is to find the maximum between the value of N and the number obtained by decimal representation of reversal of binary representation of N in a 32-bit integer. Examples: Input: N = 6Output: 1610612736Explanation: Binary representation of 6 in a 32-bit integer is 00000000000000000000000000000110 i.e., (0000
6 min read
Form a number using bit rotations of N having same frequency of each digit
Given a number N, the task is to convert it into a number in which all distinct digits have the same frequency, by rotating its bits either clockwise or anti-clockwise. If it is not possible to convert the number print -1, otherwise print the number Examples: Input: N = 331Output: 421Explanation: Binary representation of 331: 101001011After an anti
7 min read
Find a number with least sum of bit differences from given Array
Given an array arr[] and an integer L which represents the number of bits to be considered in bit representation of an array element. The task is to find a positive integer X, such that the sum of the bit difference of all the elements in arr[] with X is minimum. Examples: Input: N = 3, L = 5, arr[] = {18, 9, 21}Output: 17Explanation: arr[1] = (18)
8 min read
Article Tags :
Practice Tags :