![]() |
VOOZH | about |
You are given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to set all bits between i and j in N equal to M (e.g., M becomes a substring of N located at i and starting at j).
Examples :
Input : N = 1, M = 2, i = 2, j = 4
Output: 9
N = 00000001(Considering 8 bits only)
M = 10 (Binary of 2) For more indexes,
leading zeroes will be considered.
Now set 3 bits from ith index to j in
the N as in the M.
Bits:- 0 0 0 (0 1 0) 0 1 = 9
Indexes:- 7 6 5 4 3 2 1 0
From index 2 to 4, bits are set according
to the M.
Asked in : Adobe
A simple solution is to traverse all bits in N from 0 to 31 and set the bits equals to M in the range from i to j.
An efficient solution is to do following steps.
Output :
18Time Complexity: O(1)
Auxiliary Space: O(1)