Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Bit Manipulation

Easy
0/40
profile
Contributed by
83 upvotes

Problem statement

You have a 32-bit unsigned integer called 'num' and another integer called 'i'.


You need to perform the following operations on the 'num' integer based on the value of 'i':


1. Get the bit value at the "i"th position of "num".

2. Set the bit at the "i"th position of "num".

3. Clear the bit at the "i"th position of "num".


We are starting bits from 1 instead of 0. (1-based)


For Example:
N=25  i=3
Output : 0 29 25

Bit at the 3rd position from LSB is 0. (1 1 0 0 1)

The value of the given number after setting the 3rd bit is 29. (1 1 1 0 1)

The value of the given number after clearing the 3rd bit is 25. (1 1 0 0 1)
Detailed explanation ( Input/output format, Notes, Images )
Input format:
The first line of each test case contains an integer 'N’  denoting the number and an integer ‘i’ denoting the position of a bit from LSB in the binary representation of the 32-bit unsigned integer "num".
Output Format:
The output contains an array of 3 integers.
Note:-
You don’t need to print anything. Just implement the given function.
Sample Input 1:
9 3
Sample Output 1:
0 13 9
Explanation Of Sample Input 1:
Bit at the 3rd position from LSB is 0. ( 1 0 0 1)

The value of the given number after setting the 3rd bit is 13. ( 1 1 0 1)

The value of the given number after clearing the 3rd bit is 9. (1 0 0 1)
Sample Input 2:
11 2
Sample Output 2:
1 11 9
Explanation Of Sample Input 2:
The 2nd position from LSB is 1. (1 0 1 1)

The value of the given number after setting the 2nd bit is 11. (1 0 1 1)

The value of the given number after clearing the 2nd bit is 9. (1 0 0 1)
Constraints:
0 <= num <= 10^9
1 <= i <= 32
Time Limit: 1 sec
Follow Up:
Can you solve this in O(1) time?
Hint

Using bitwise operators

Approaches (1)
Bit manipulation

Approach:

  1. Get the bit value at the "i"th position of "num":
    • Create a mask with a 1 in the "i"th position and 0 in all other positions.
    • Use a bitwise AND operation between "num" and the mask to extract the bit value at the "i"th position of "num".
    • If the result is non-zero, then the bit at the "i"th position of "num" is set, otherwise, it is clear.
  2. Set the bit at the "i"th position of "num":
    • Create a mask with a 1 in the "i"th position and 0 in all other positions.
    • Use a bitwise OR operation between "num" and the mask to set the bit at the "i"th position of "num".
  3. Clear the bit at the "i"th position of "num":
    • Create a mask with a 0 in the "i"th position and 1 in all other positions.
    • Use a bitwise AND operation between "num" and the mask to clear the bit at the "i"th position of "num".


 

Algorithm:

  • Initialize variables ‘get’, ‘set’ and ‘clear’ to zero
  • Initialize ‘mask’ by left shifting 1 by (i-1) bits.
  • If ‘num’ AND ‘mask’ >=1 then
    • ‘get’=1
  • ‘set’= ‘num’ OR ‘mask’
  • ‘mask’ = NOT ‘mask’
  • ‘clear’ = ‘mask’ AND ‘num’
  • Store ‘set’, ‘get’ and ‘clear’ in an array ‘arr’
  • Return arr
Time Complexity

O(1)

We are simply using bitwise operators therefore time complexity is O(1).

Space Complexity

O(1)

No extra space is used. Hence, the space complexity is O(1).

Code Solution
(100% EXP penalty)
Bit Manipulation
All tags
Sort by
Search icon

Interview problems

Simplest Cpp Solution|Easy to understand

vector<int> bitManipulation(int num, int i){

    // Write your code here.

  vector<int> ans;

    int p=pow(2,i-1);

    if((num&p)==0)

    {

        ans.push_back(0);

        ans.push_back(num+p);

        ans.push_back(num);

    }

    else

    {

        

        ans.push_back(1);

        ans.push_back(num);

        ans.push_back(num-p);

    }

    return ans;

}

13 views
0 replies
1 upvote

Interview problems

easy get,set,clear bit

    public static int[] bitManipulation(int num, int i){
        i--;
        int setbit = (num | (1<<i));
        int clearbit = (num  & (~(1<<i)) );
        int getbit = (1 & (num>>i));
        return new int[]{getbit,setbit,clearbit};
    }
12 views
0 replies
0 upvotes

Interview problems

Solution in java

public static int[] bitManipulation(int num, int i){

        return new int[]{num>>i-1 & 1,num | (1<<(i-1)),num & (~(1<<(i-1))) };

    }

23 views
0 replies
1 upvote

Interview problems

java easiest solution by bit manipulation

public static int[] bitManipulation(int num, int i){

        // Write your code here.

        //get the ith postitioon of bit

        int get=(num & (1<<(i-1)))>0?1:0;

 

        // set the ith bit 

        int set=(num | (1 << i-1));

        

        // clear the ith bit 

        int clear=(num & ~(1<< i-1));

 

        int[] sum=new int[]{get,set,clear};

        return sum;

    }

40 views
0 replies
0 upvotes

Interview problems

sol

vector<int> bitManipulation(int num, int i) {

    i=i-1;

    // Initialize a bitmask with the i-th bit set to 1

    int mask = 1 << i;

 

    // Extract the i-th bit from 'num'

    int extractedBit = (num >> i) & 1;

 

    // Set the i-th bit of 'num' to 1

    int setBit = num | mask;

 

    // Clear the i-th bit of 'num' (set it to 0)

    int clearedBit = num & ~mask;

 

    vector<int> result = {extractedBit, setBit, clearedBit};

    return result;

}

202 views
0 replies
0 upvotes

Interview problems

Can anyone tell me where is wrong in my code why its not working against the test cases.

#include <bits/stdc++.h> 

#include <string>

#include <iostream>

using namespace std;

 

int binaryToDecimal(string s)

{

    int num=0,pow=1;

    for (int i = s.length()-1;i>=0; i--) {

      if(s[i]=='1')

        num=num+pow;

      pow*=2;

    }

    return num;

}

 

vector<int> bitManipulation(int num, int i){

    vector<int> ans;

    string s="";

    while(num>0)

    {

        if(num%2==1)

            s=s+'1';

        else

            s=s+'0';

        num=num/2;

    }

    

    

    char ch=s[i-1];

   int position=ch-'0';

   ans.push_back(position);

 

   s[i-1]='1';

   int num1=binaryToDecimal(s);

 

   s[i-1]='0';

   int num2=binaryToDecimal(s);

 

   ans.push_back(num1);

   ans.push_back(num2);

 

   return ans;

}

programming

105 views
1 reply
0 upvotes

Interview problems

C++ Solution

#include <bits/stdc++.h>
vector<int> bitManipulation(int num, int i){
    vector<int> ans;
    int val=num/(pow(2,i-1));
    int bit;
    if(val%2==0) bit=0;
    else bit=1;
    ans.push_back(bit);

    if(bit==1){ 
        ans.push_back(num);
        ans.push_back(num-pow(2,i-1));
    }

    else{ 
        ans.push_back(num+pow(2,i-1));
        ans.push_back(num);
    }
    return ans;
}
303 views
0 replies
0 upvotes

Interview problems

Bit manipulation O(N) || JAVA

public class Solution {

    public static int[] bitManipulation(int num, int i){

        int value =(num &(1<<i-1)) >0?1:0;

        int set = (num |(1<<i-1));

        int clear = (num & (~(1<<i-1)));

        int[] sum =new int[] {value,set,clear};

        return sum;

    }

}

189 views
0 replies
1 upvote

Interview problems

java solution uisng Bit Manipulation 100% works

public class Solution {

    public static int[] bitManipulation(int num, int i){

        // Write your code here.

        int a[]=new int[3];

        int manish;

        if((num & 1<<i-1)==0){

            manish=0;

        }

        else{

            manish=1;

        }

        a[0]=manish;

        a[1] =  num |(1<<i-1);

        a[2]= num &(~(1<<i-1));

        return a;

    }

}

 

96 views
0 replies
0 upvotes

Interview problems

what is wrong in this

vector<int> bitManipulation(int num, int i) {

  int numi1, numi0;

  vector<int> ans;

  //getting the ith bit

  if(num&(1<<i) != 0){

      ans.push_back(1);

  }else{

      ans.push_back(0);

  }

 

  //setting the ith position

  ans.push_back(num|(1<<i));

 

  //clearing the ith positon

  ans.push_back(num&(~(1<<i)));

 

  return ans;

}

70 views
1 reply
0 upvotes
Full screen
Console