Count number of bits to be flipped to convert A to B | Set-2
Given two integers A and B, the task is to count the number of bits needed to be flipped to convert A to B.
Examples:
Input: A = 10, B = 7
Output: 3
binary(10) = 1010
binary(7) = 0111
1010
0111
3 bits need to be flipped.
Input: A = 8, B = 7
Output: 4
Approach: An approach to solve this problem has already been discussed here. Here, the count of bits that need to be flipped can be found by matching all the bits in both the integers one by one. If the bit under consideration differs then increment the count.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countBits( int a, int b)
{
int count = 0;
while (a || b) {
int last_bit_a = a & 1;
int last_bit_b = b & 1;
if (last_bit_a != last_bit_b)
count++;
a = a >> 1;
b = b >> 1;
}
return count;
}
int main()
{
int a = 10, b = 7;
cout << countBits(a, b);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int countBits( int a, int b)
{
int count = 0 ;
while (a > 0 || b > 0 )
{
int last_bit_a = a & 1 ;
int last_bit_b = b & 1 ;
if (last_bit_a != last_bit_b)
count++;
a = a >> 1 ;
b = b >> 1 ;
}
return count;
}
public static void main(String[] args)
{
int a = 10 , b = 7 ;
System.out.println(countBits(a, b));
}
}
|
Python3
def countBits(a, b):
count = 0
while (a or b):
last_bit_a = a & 1
last_bit_b = b & 1
if (last_bit_a ! = last_bit_b):
count + = 1
a = a >> 1
b = b >> 1
return count
a = 10
b = 7
print (countBits(a, b))
|
C#
using System;
class GFG
{
static int countBits( int a, int b)
{
int count = 0;
while (a > 0 || b > 0)
{
int last_bit_a = a & 1;
int last_bit_b = b & 1;
if (last_bit_a != last_bit_b)
count++;
a = a >> 1;
b = b >> 1;
}
return count;
}
public static void Main(String[] args)
{
int a = 10, b = 7;
Console.WriteLine(countBits(a, b));
}
}
|
Javascript
<script>
function countBits(a, b)
{
var count = 0;
while (a || b) {
var last_bit_a = a & 1;
var last_bit_b = b & 1;
if (last_bit_a != last_bit_b)
count++;
a = a >> 1;
b = b >> 1;
}
return count;
}
var a = 10, b = 7;
document.write(countBits(a, b));
</script>
|
Time Complexity: O(min(log a, log b))
Auxiliary Space: O(1)
Last Updated :
17 Nov, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...