![]() |
VOOZH | about |
Given a string "s" and an integer "m" your objective is to calculate the remainder "r" when the decimal value of binary string "s" is divided by "m".
Examples:
Input: s = "101", m = 2
Output: 1
Explanation: If we have a string "(101)" its decimal equivalent is "(5)". Therefore if we compute 5 mod 2 the result will be 1.Input: s = "1000", m = 4
Output: 0
Explanation: If we have a string "(1000)" and m = 4 then r can be calculated as k mod m, which, in this case's 8 mod 4. The final result will be 0.
Approach: To solve the problem
The idea is to calculate the value of each corresponding set bit and use it right away without storing it in an array, as we know the value of every higher set bit is 2x of the previous set bit so we can simply use a variable power and at every bit we multiply power with 2 to get the value of the current ithbit (value of 2i).
Steps for Implementing the above Approach:
Below is the implementation of the above idea:
1
Time Complexity:- O(N), As we are only using a single loop over the size of binary string.
Auxiliary Space:- O(1), As we are not using any extra space.