Pages

Saturday, May 3, 2025

Q. Clear range from ith to jth bit (Bit Manipulation)

 #include <iostream>

using namespace std;

// goal- to clear from left and right bit of number

int main()

{

    int i = 1, j = 3;

    int num = 31; // 0b01111


    int left = ~0 << (j + 1);       // Clears bits j and above

    int right = (1 << i) - 1;       // Sets bits below i

    int bitMask = left | right;     // Clears bits from i to j

    int result = num & bitMask;     // Apply the mask


    cout << "Bitmask: " << bitMask << endl;

    cout << "Result: " << result << endl;


    return 0;

}


No comments:

Post a Comment

3Sum - Leetcode solution - How i turned into two-pointer approach?

  class Solution {     public List < List < Integer >> threeSum ( int [] nums ) {         Arrays . sort (nums); // first sort...