Set Nth Bit

00:00
EasyBit ManipulationBitwise OperationsInteger

Given a non-negative integer num and a 1-indexed bit position n, your task is to return the new number after setting the n-th bit of num to 1. If the n-th bit is already 1, it should remain 1. All other bits should remain unchanged.

The bits are 1-indexed from the rightmost (least significant) bit. For example, n=1 refers to the rightmost bit, n=2 refers to the second bit from the right, and so on.

Examples:

Example 1: Input: num = 13, n = 2 Output: 15 Explanation: Binary of 13: ...01101 The 2nd bit (from the right) is 0. Setting the 2nd bit to 1 results in ...01111, which is 15 in decimal.

Example 2: Input: num = 7, n = 3 Output: 7 Explanation: Binary of 7: ...00111 The 3rd bit (from the right) is already 1. Setting it to 1 again leaves the number unchanged.

Example 3: Input: num = 0, n = 1 Output: 1 Explanation: Binary of 0: ...00000 Setting the 1st bit to 1 results in ...00001, which is 1 in decimal.

Constraints:

  • 0 <= num <= 2 * 10^9
  • 1 <= n <= 31

Examples

Input → num = 13, n = 2
Output → 15
Input → num = 7, n = 3
Output → 7
Input → num = 0, n = 1
Output → 1