Sunday, October 21, 2012

BitManipulation1

Q1. Write a function int BitSwapReqd(int A, int B) to determine the number of bits required to convert integer A to integer B.
input: 31, 14
output: 2

Answer:

public class BitManipulation1 {
    public static int requiredBitSwap(int a, int b) {
        int count = 0;
        for (int c = a ^ b; c != 0; c = c >> 1) {
            count += c & 1;
        }
        return count;
    }

    public static void main(String[] args) {
        System.out.println(requiredBitSwap(31, 14));
        System.out.println(requiredBitSwap(0, 15));
    }
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.