Posts Toggle bits in the given range (geeksforgeeks - SDE Sheet)
Post
Cancel

Toggle bits in the given range (geeksforgeeks - SDE Sheet)

PROBLEM DESCRIPTION

Given a non-negative number n and two values l and r. The problem is to toggle the bits in the range l to r in the binary representation of n, i.e., to toggle bits from the lth least significant bit to the rth least significant bit (the rightmost bit as counted as the first bit).

geeksforgeeks

SOLUTION

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {

    static int toggleBits(int n , int l , int r) {

        for(int i=l; i<=r; i++){
            n = (n ^ (1 << i-1));
        }

        return n;

    }

};
This post is licensed under CC BY 4.0 by the author.