Friday, July 15, 2016

Bitwise operations

Flip Bits

Determine the number of bits required to flip if you want to convert integer n to integer m.

I feel glad to come up solution on this and pass the OJ with one pass. It might be easy, but it's from here I gain confidence on bitwise operations.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public static int bitSwapRequired(int a, int b) {
        // write your code here
        int c = a^b;
        //1.xor operation leave difference with 1s
        //2. n&(n-1) will remove last 1
        int cnt=0;
        while(c!=0){
            cnt++;
            c = c&(c-1);
        }
        return cnt;
    }
Check power of 2
1
2
3
4
5
6
public boolean checkPowerOf2(int n) {
        // write your code here
        //n&(n-1) will remove last 1, 2's power has only one 1 in it
       
        return (n>=1&&(n&(n-1))==0);
    }

No comments: