Given two binary numbers strings and of length . Find the number of ways of swapping two bits in s1(only s1 not s2) so that bit-wise OR of these two numbers s1 and s2 are changed.
Note: The length of both string must be equal, you can take leading zeros in case of different length.
Input: s1 = "01011", s2 = "11001" Output: 4 Explanation: You can swap the bit of s1 at indexed: (1, 4), (2, 3), (3, 4) and (3, 5) there are 4 ways possible. Input: s1 = "011000", s2 = "010011" Output: 6
Approach: Initialize a variable result as zero that stores number of ways to swap bits of s1 so that bitwise OR of s1 and s2 changes. Initialize four variables say , , , and as zero.
Traverse both strings from left side and check for the below conditions to increment values of the
variable declared above:
- If the current bit of both s1 and s2 are zero, increment c.
- If current bit of s2 is zero and s1 is one, increment d.
- If current bit of s2 is one and s1 is zero, increment a.
- If current bit of both s1 and s2 is one, increment b.
Update the result by (a*d) + (b*c) + (c*d) and return the result.
Below is the implementation of the above approach:
- Total pairs in an array such that the bitwise AND, bitwise OR and bitwise XOR of LSB is 1
- Largest even number possible by using one swap operation in given number
- Swap bits in a given number
- Bit manipulation | Swap Endianness of a number
- Largest number with one swap allowed
- Leftover element after performing alternate Bitwise OR and Bitwise XOR operations on adjacent pairs
- Next higher number using atmost one swap operation
- Form the smallest number using at most one swap operation
- Bitwise OR( | ) of all even number from 1 to N
- Number of subarrays have bitwise OR >= K
- Print bitwise AND set of a number N
- Number of ways to split a binary number such that every part is divisible by 2
- Number of pairs with Bitwise OR as Odd number
- Multiply any Number with 4 using Bitwise Operator
- Count pairs with Bitwise XOR as ODD number
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.