712531. Bit Manipulation

Easy

Bit Manipulation

Summary

This problem is about manipulating bits in a given number. You are asked to perform various operations on the bits, such as setting or clearing specific positions, checking if a bit is set at a certain position, and so on. This problem requires you to understand how binary numbers work and how to use bitwise operators to manipulate them.

Detailed Explanation

The key concept involved in this problem is bitwise manipulation. You will need to use the following bitwise operators:

  • & (bitwise AND)
  • | (bitwise OR)
  • ^ (bitwise XOR)
  • ~ (bitwise NOT)

To solve this problem, you can start by defining a function that takes an integer as input and performs the desired operations on its bits. For example, if you want to set the bit at position i, you can use the following formula:

num |= 1 << i;

This shifts the binary number 1 to the left by i positions and then ORs it with the original number. This effectively sets the bit at position i.

To check if a bit is set at a certain position, you can use the following formula:

return (num & (1 << i)) != 0;

This shifts the binary number 1 to the left by i positions and then ANDs it with the original number. If the result is not zero, it means that the bit at position i is set.

Here's a step-by-step breakdown of the solution:

  1. Define a function setBit(n, i) that takes an integer n and an integer i as input.
  2. Use the formula above to set the bit at position i.
  3. Return the updated number.

Time complexity: O(1) Space complexity: O(1)

Optimized Solutions

Java

public class BitManipulation {
    public static int setBit(int n, int i) {
        return n | (1 << i);
    }
}

Python

def set_bit(n, i):
    return n | (1 << i)

C++

class BitManipulation {
public:
    int setBit(int n, int i) {
        return n | (1 << i);
    }
};

JavaScript

function setBit(n, i) {
    return n | (1 << i);
}
View on GeeksforGeeks

Not available

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.