Set a Specified Bit
Given non-negative integers n and bitIndex, return n with the zero-based bit at bitIndex set to 1. Leave every other bit unchanged. Bit index 0 is the…
Given non-negative integers n and bitIndex, return n with the zero-based bit at bitIndex set to 1. Leave every other bit unchanged. Bit index 0 is the least-significant bit. Setting a bit that is already 1 leaves n unchanged.
0 <= n <= 2147483647 and 0 <= bitIndex <= 30. Both arguments are separate signed-int32 values. The result is at most 2147483647.
Example 1: input n = 10, bitIndex = 0; output 11. The binary representation 1010 becomes 1011; bit 0 changes and bit 1 remains set.
Example 2: input n = 10, bitIndex = 1; output 10. Bit 1 is already 1, so setting it leaves the value unchanged.
Example 3: input n = 0, bitIndex = 3; output 8. Setting bit 3 creates the value 1000 in binary.
Category: Math & Numbers. Topic: math. Difficulty: Easy. Patterns: bit-manipulation.