Given an integer N, the task is to find the minimum number of bits required to be flipped to convert the binary representation of N into a palindrome.
Examples:
_Input: __N = 12 _
_Output: __2 _
Explanation:
_Binary String representing 12 = “1100”. _
_To make “1100” a palindrome, convert the string to “0110”. _
Therefore, minimum bits required to be flipped is 2.
_Input: __N = 7 _
_Output: __0 _
Explanation:
_Binary String representing 7 = 111, which is already a palindrome. _
Recommended: Please try your approach on {IDE} first, before moving on to the solution.
**Naive Approach: **The simplest way is to check for every possible subset that is a palindrome having the same number of bits.
_Time Complexity: _O(N)
_Auxiliary Space: _O(1)
**Efficient Approach: **The above approach can be optimized through these steps:
Below is the implementation of the above approach:
// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
**using**
**namespace**
std;
// Function to calculate the
// length of the binary string
**int**
check_length(``**int**
n)
{
// Length
**int**
ans = 0;
**while**
(n) {
// Right shift of n
n = n >> 1;
// Increment the length
ans++;
}
// Return the length
**return**
ans;
}
// Function to check if the bit present
// at i-th position is a set bit or not
**int**
check_ith_bit(``**int**
n,
**int**
i)
{
// Returns true if the bit is set
**return**
(n & (1 << (i - 1)))
?
**true**
:
**false**``;
}
// Function to count the minimum
// number of bit flips required
**int**
no_of_flips(``**int**
n)
{
// Length of the binary form
**int**
len = check_length(n);
// Number of flips
**int**
ans = 0;
// Pointer to the LSB
**int**
right = 1;
// Pointer to the MSB
**int**
left = len;
**while**
(right < left) {
// Check if the bits are equal
**if**
(check_ith_bit(n, right)
!= check_ith_bit(n, left))
ans++;
// Decrementing the
// left pointer
left--;
// Incrementing the
// right pointer
right++;
}
// Returns the number of
// bits to flip.
**return**
ans;
}
// Driver Code
**int**
main()
{
**int**
n = 12;
cout << no_of_flips(n);
**return**
0;
}
Output:
2
Time Complexity:_ O(log N)_
Auxiliary Space:_ O(1)_
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
#bit magic #greedy #mathematical #strings #palindrome