Bits Count – Y to X

The program must accept two integers X and Y where X is always greater than or equal to Y. The program must print the count of bits C that must be changed in Y so that it becomes X.

Boundary Condition(s):
1 <= Y <= X <= 10^8

Input Format:
The first line contains X and Y separated by a space.

Output Format:
The first line contains an integer value representing C.

Example Input/Output 1:
Input:
5 4
Output:
1
Explanation:
The binary representation of X-5 is 101. The binary representation of Y=4 is 100. Changing the last bit, we can get 5 which is X. Hence the output is 1.

Example Input/Output 2:
Input:
10 6
Output:
2

x, y = map(int, input().split())
diff = x ^ y
count = bin(diff).count('1')
print(count)
#include <iostream>
using namespace std;

int countSetBits(int n) {
    int count = 0;
    while (n) {
        count += n & 1;
        n >>= 1;
    }
    return count;
}

int main() {
    int x, y;
    cin >> x >> y;
    int diff = x ^ y;
    cout << countSetBits(diff);
    return 0;
}
import java.util.Scanner;

public class BitsCountYtoX {

    public static int countSetBits(int n) {
        int count = 0;
        while (n > 0) {
            count += n & 1;
            n >>= 1;
        }
        return count;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int x = scanner.nextInt();
        int y = scanner.nextInt();
        int diff = x ^ y;
        System.out.println(countSetBits(diff));
    }
}
#include <stdio.h>

int countSetBits(int n) {
    int count = 0;
    while (n) {
        count += n & 1;
        n >>= 1;
    }
    return count;
}

int main() {
    int x, y;
    scanf("%d %d", &x, &y);
    int diff = x ^ y;
    printf("%d", countSetBits(diff));
    return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

More posts. You may also be interested in.