Topics Index

Number Of Bits Flipped

If you need explanation Read this topic

If you need Answer Take test on this topic

Number Of Bits Flipped
What will be the output of the following program?
public class NumberOfBitsFlipped {
    public static void main(String s[]) {
        int fromNumber = 9, toNumber = 3;
        System.out.println("No.of bits needed to be flipped to convert "
                + fromNumber + " to " + toNumber
                + " is " + getNumberOfFlips(fromNumber, toNumber));
    public static int getNumberOfFlips(int fromNumber, int toNumber) {
        String s1 = Integer.toBinaryString(fromNumber);
        String s2 = Integer.toBinaryString(toNumber);
        String max, min;
        if (s1.compareTo(s2) > 0) {
            max = s1;
            min = s2;
        } else {
            max = s2;
            min = s1;
        int count = max.length() - min.length();
        for (int i = 0; i < min.length(); i++)
            if (min.charAt(i) != max.charAt(i))
        if (s1.equals(s2))
            count = 0;
        return count;

A. No.of bits needed to be flipped to convert 9 to 3 is 0
B. No.of bits needed to be flipped to convert 9 to 3 is 1
C. No.of bits needed to be flipped to convert 9 to 3 is 2
D. Some other output
E. Compilation Error or Runtime Error
Topic: Java BitSet

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

B since integers converted to binary s1 does not equal to s1 (since binary and 9 and 3) except the last binary bit hence answer is B

Posted by Karthik Narahari    2014-01-30 12:46:32

ans is E...runtime conversion of 3 to binarystring results in 11...and 9 to 1001...s2 is lexographically greater than s1...else is the length of min string is greater so the for loop generates index out of bounds exception

Posted by Santosh Munugota    2014-01-30 12:50:11


Posted by Kick Bhasha    2014-01-30 12:51:47

Congratulations Santosh Munugota . You are this dose winner. We will send you the link using which you can claim your recharge.

Posted by Merit Campus    2014-01-31 05:39:01

© meritcampus 2019

All Rights Reserved.

Open In App