Count number of bits to be flipped to convert A to B
Last Updated :
25 Apr, 2023
Given two numbers A and B. Write a program to count the number of bits needed to be flipped to convert A to B.
Examples:
Input: A = 10, B = 20
Output: 4
Explanation: Binary representation of A is 00001010
Binary representation of B is 00010100
We need to flip highlighted four bits in A to make it B.
Input: A = 7, B = 10
Output: 3
Explanation: Binary representation of A is 00000111
Binary representation of B is 00001010
We need to flip highlighted three bits in A to make it B.
Count the number of bits to be flipped to convert A to B using the XOR operator:
To solve the problem follow the below idea:
Calculate (A XOR B), since 0 XOR 1 and 1 XOR 0 is equal to 1. So calculating the number of set bits in A XOR B will give us the count of the number of unmatching bits in A and B, which needs to be flipped
Follow the given steps to solve the problem:
- Calculate the XOR of A and B
- Count the set bits in the above-calculated XOR result
- Return the count
Below is the implementation of the above approach:
C
#include <stdio.h>
int countSetBits( int n)
{
int count = 0;
while (n > 0) {
count++;
n &= (n - 1);
}
return count;
}
int FlippedCount( int a, int b)
{
return countSetBits(a ^ b);
}
int main()
{
int a = 10;
int b = 20;
printf ( "%d\n" , FlippedCount(a, b));
return 0;
}
|
C++
#include <bits/stdc++.h>
using namespace std;
int countSetBits( int n)
{
int count = 0;
while (n > 0) {
count++;
n &= (n - 1);
}
return count;
}
int FlippedCount( int a, int b)
{
return countSetBits(a ^ b);
}
int main()
{
int a = 10;
int b = 20;
cout << FlippedCount(a, b) << endl;
return 0;
}
|
Java
import java.util.*;
class Count {
public static int countSetBits( int n)
{
int count = 0 ;
while (n != 0 ) {
count++;
n &= (n - 1 );
}
return count;
}
public static int FlippedCount( int a, int b)
{
return countSetBits(a ^ b);
}
public static void main(String[] args)
{
int a = 10 ;
int b = 20 ;
System.out.print(FlippedCount(a, b));
}
}
|
Python3
def countSetBits(n):
count = 0
while n:
count + = 1
n & = (n - 1 )
return count
def FlippedCount(a, b):
return countSetBits(a ^ b)
if __name__ = = "__main__" :
a = 10
b = 20
print (FlippedCount(a, b))
|
C#
using System;
class Count {
public static int countSetBits( int n)
{
int count = 0;
while (n != 0) {
count++;
n &= (n - 1);
}
return count;
}
public static int FlippedCount( int a, int b)
{
return countSetBits(a ^ b);
}
public static void Main()
{
int a = 10;
int b = 20;
Console.WriteLine(FlippedCount(a, b));
}
}
|
PHP
<?php
function countSetBits( $n )
{
$count = 0;
while ( $n )
{
$count += 1;
$n &= (n-1);
}
return $count ;
}
function FlippedCount( $a , $b )
{
return countSetBits( $a ^ $b );
}
$a = 10;
$b = 20;
echo FlippedCount( $a , $b );
?>
|
Javascript
function countSetBits(n) {
var count = 0;
while (n != 0) {
count++;
n &= (n - 1);
}
return count;
}
function FlippedCount(a , b) {
return countSetBits(a ^ b);
}
var a = 10;
var b = 20;
document.write(FlippedCount(a, b));
|
Time Complexity: O(K) where K is the number of bits
Auxiliary Space: O(1)
Note: Set bits in (a XOR b) can also be computer using built in function __builtin_popcount() in C/C++
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int b = 20;
cout <<__builtin_popcount(a^b) << endl;
return 0;
}
|
C
#include <stdio.h>
int main()
{
int a = 10;
int b = 20;
printf ( "%d\n" ,__builtin_popcount(a^b));
return 0;
}
|
Java
public class Main {
public static void main(String[] args) {
int a = 10 ;
int b = 20 ;
System.out.println(Integer.bitCount(a ^ b));
}
}
|
Python3
if __name__ = = '__main__' :
a = 10
b = 20
result = bin (a ^ b).count( "1" )
print (result)
|
C#
using System;
class Program
{
static void Main( string [] args)
{
int a = 10;
int b = 20;
Console.WriteLine(BitCount(a ^ b));
}
static int BitCount( int value)
{
int count = 0;
while (value != 0)
{
count += value & 1;
value >>= 1;
}
return count;
}
}
|
Javascript
function countBits(a, b) {
return (a ^ b).toString(2).split( '1' ).length-1;
}
let a = 10;
let b = 20;
console.log(countBits(a, b));
|
Time Complexity: O(K) where K is the number of bits
Auxiliary Space: O(1)
Count the number of bits to be flipped to convert A to B using the AND operator:
To solve the problem follow the below idea:
Start comparing the bits in A and B, starting from the least significant bit and if (A & 1) is not equal to (B & 1) then the current bit needs to be flipped, as the value of bits is different at this position in both the numbers
Follow the given steps to solve the problem:
- Declare variable flips equal to zero
- Run a loop, while a is greater than zero and b is also greater than zero
- Calculate values of (A AND 1) and (B AND 1)
- If these values are not equal then increase the flip value by 1
- Right shift a and b by 1
- Return flips
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int countFlips( int a, int b)
{
int flips = 0;
while (a > 0 || b > 0) {
int t1 = (a & 1);
int t2 = (b & 1);
if (t1 != t2) {
flips++;
}
a >>= 1;
b >>= 1;
}
return flips;
}
int main()
{
int a = 10;
int b = 20;
cout << countFlips(a, b);
}
|
Java
import java.io.*;
class GFG {
public static int countFlips( int a, int b)
{
int flips = 0 ;
while (a > 0 || b > 0 ) {
int t1 = (a & 1 );
int t2 = (b & 1 );
if (t1 != t2) {
flips++;
}
a >>>= 1 ;
b >>>= 1 ;
}
return flips;
}
public static void main(String[] args)
{
int a = 10 ;
int b = 20 ;
System.out.println(countFlips(a, b));
}
}
|
Python3
def countFlips(a, b):
flips = 0
while (a > 0 or b > 0 ):
t1 = (a & 1 )
t2 = (b & 1 )
if (t1 ! = t2):
flips + = 1
a >> = 1
b >> = 1
return flips
if __name__ = = "__main__" :
a = 10
b = 20
print (countFlips(a, b))
|
C#
using System;
class GFG {
public static int countFlips( int a, int b)
{
int flips = 0;
while (a > 0 || b > 0) {
int t1 = (a & 1);
int t2 = (b & 1);
if (t1 != t2) {
flips++;
}
a >>= 1;
b >>= 1;
}
return flips;
}
public static void Main(String[] args)
{
int a = 10;
int b = 20;
Console.Write(countFlips(a, b));
}
}
|
Javascript
function countFlips(a, b){
var flips = 0;
while (a>0 || b>0){
var t1 = (a&1);
var t2 = (b&1);
if (t1!=t2){
flips++;
}
a>>>=1;
b>>>=1;
}
return flips;
}
var a = 10;
var b = 20;
document.write(countFlips(a, b));
|
Time Complexity: O(K) where K is the number of bits
Auxiliary Space: O(1)
Count the number of bits to be flipped to convert A to B:-
To solve this we just need to do a few simple steps. To know more follow the below steps:-
Approach:
- Convert A and B to binary numbers.
- Compare using ‘equal to’ operator if equal then return 0 otherwise iterate and
- compare the ith of A to ith of B and count the operations
- print the count.
C++
#include <bits/stdc++.h>
using namespace std;
string binary( int num)
{
string str = "" ;
while (num) {
if (num & 1)
str += '1' ;
else
str += '0' ;
num >>= 1;
}
reverse(str.begin(), str.end());
return str;
}
int main()
{
int a = 10;
int b = 20;
string astr = binary(a);
string bstr = binary(b);
int na = astr.size(), nb = bstr.size();
int cnt = 0;
int diff = abs (na - nb);
if (na > nb) {
for ( int i = 0; i < diff; i++) {
if (astr[i] == '1' ) {
cnt++;
}
}
}
else if (na < nb) {
for ( int i = 0; i < diff; i++) {
if (bstr[i] == '1' ) {
cnt++;
}
}
}
na = na - 1;
nb = nb - 1;
while (na >= 0 and nb >= 0) {
if (astr[na] != bstr[nb]) {
cnt++;
}
na--;
nb--;
}
cout << cnt << endl;
return 0;
}
|
Java
import java.util.*;
public class Main {
public static String binary( int num) {
String str = "" ;
while (num > 0 ) {
if ((num & 1 ) == 1 )
str += '1' ;
else
str += '0' ;
num >>= 1 ;
}
return new StringBuilder(str).reverse().toString();
}
public static void main(String[] args) {
int a = 10 ;
int b = 20 ;
String astr = binary(a);
String bstr = binary(b);
int na = astr.length(), nb = bstr.length();
int cnt = 0 ;
int diff = Math.abs(na - nb);
if (na > nb) {
for ( int i = 0 ; i < diff; i++) {
if (astr.charAt(i) == '1' ) {
cnt++;
}
}
}
else if (na < nb) {
for ( int i = 0 ; i < diff; i++) {
if (bstr.charAt(i) == '1' ) {
cnt++;
}
}
}
na = na - 1 ;
nb = nb - 1 ;
while (na >= 0 && nb >= 0 ) {
if (astr.charAt(na) != bstr.charAt(nb)) {
cnt++;
}
na--;
nb--;
}
System.out.println(cnt);
}
}
|
Python3
def binary(num):
str = ""
while num:
if num & 1 :
str + = '1'
else :
str + = '0'
num >> = 1
return str [:: - 1 ]
a = 10
b = 20
astr = binary(a)
bstr = binary(b)
na, nb = len (astr), len (bstr)
cnt = 0
diff = abs (na - nb)
if na > nb:
for i in range (diff):
if astr[i] = = '1' :
cnt + = 1
elif na < nb:
for i in range (diff):
if bstr[i] = = '1' :
cnt + = 1
na - = 1
nb - = 1
while na > = 0 and nb > = 0 :
if astr[na] ! = bstr[nb]:
cnt + = 1
na - = 1
nb - = 1
print (cnt)
|
C#
using System;
public class Program
{
static string Binary( int num)
{
string str = "" ;
while (num != 0)
{
if ((num & 1) == 1)
str += '1' ;
else
str += '0' ;
num >>= 1;
}
char [] charArray = str.ToCharArray();
Array.Reverse(charArray);
return new string (charArray);
}
public static void Main()
{
int a = 10;
int b = 20;
string astr = Binary(a);
string bstr = Binary(b);
int na = astr.Length, nb = bstr.Length;
int cnt = 0;
int diff = Math.Abs(na - nb);
if (na > nb)
{
for ( int i = 0; i < diff; i++)
{
if (astr[i] == '1' )
{
cnt++;
}
}
}
else if (na < nb)
{
for ( int i = 0; i < diff; i++)
{
if (bstr[i] == '1' )
{
cnt++;
}
}
}
na = na - 1;
nb = nb - 1;
while (na >= 0 && nb >= 0)
{
if (astr[na] != bstr[nb])
{
cnt++;
}
na--;
nb--;
}
Console.WriteLine(cnt);
}
}
|
Javascript
function binary(num) {
let str = '' ;
while (num) {
if (num & 1) str += '1' ;
else str += '0' ;
num >>= 1;
}
return str.split( '' ).reverse().join( '' );
}
let a = 10;
let b = 20;
let astr = binary(a);
let bstr = binary(b);
let na = astr.length;
let nb = bstr.length;
let cnt = 0;
let diff = Math.abs(na - nb);
if (na > nb) {
for (let i = 0; i < diff; i++) {
if (astr[i] === '1' ) cnt++;
}
} else if (na < nb) {
for (let i = 0; i < diff; i++) {
if (bstr[i] === '1' ) cnt++;
}
}
na--;
nb--;
while (na >= 0 && nb >= 0) {
if (astr[na] !== bstr[nb]) cnt++;
na--;
nb--;
}
console.log(cnt);
|
Time complexity- O(log N)
Auxiliary Space – O(N)
Thanks to Sahil Rajput for providing the above implementation.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...