Given two binary strings A and B of length N and M (up to 105). The task is to repeat the below process and find the answer.
Initialize ans = 0 while (B > 0) ans += A & B (bitwise AND) B = B / 2 print ans
Note: Answer can be very large so print Answer % 1000000007.
Input: A = "1001", B = "10101" Output: 11 1001 & 10101 = 1, ans = 1, B = 1010 1001 & 1010 = 8, ans = 9, B = 101 1001 & 101 = 1, ans = 10, B = 10 1001 & 10 = 0, ans = 10, B = 1 1001 & 1 = 1, ans = 11, B = 0 Input: A = "1010", B = "1101" Output: 12
Approach: Since only B is getting affected in all the iterations and dividing a binary number by 2 means right shifting it by 1 bit, it can be observed that a bit in A will only be affected by the set bits in B which are on the left i.e. more significant than the current bit (including the current bit). For example, A = “1001” and B = “10101”, the least significant bit in A will only be affected by the set bits in B i.e. 3 bits in total and the most significant bit in A will only be affected by a single set bit in B i.e. the most significant bit in B as all the other set bits will not affect it in any iteration of the loop while performing bitwise AND, so the final result will be 20 * 3 + 23 * 1 = 3 + 8 = 11.
Below is the implementation of the above approach.
- Add n binary strings
- Program to add two binary strings
- Bitwise AND of N binary strings
- Generate all binary strings from given pattern
- Generate all the binary strings of N bits
- Count number of binary strings of length N having only 0's and 1's
- Count of non-overlapping sub-strings "101" and "010" in the given binary string
- Count binary strings with twice zeros in first half
- Count number of binary strings without consecutive 1's
- Number of Binary Strings of length N with K adjacent Set Bits
- Generate all binary strings of length n with sub-string "01" appearing exactly twice
- Find the number of binary strings of length N with at least 3 consecutive 1s
- Find a permutation of 2N numbers such that the result of given expression is exactly 2K
- Count binary strings with k times appearing adjacent two set bits
- Minimum positive integer to divide a number such that the result is an odd
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.