Tuesday, July 11, 2017

Number with same weight


public class ClosestInSameBitCount {

    

    public static final int NUM_UNSIGN_BITS=63;

    /*
        Problem: Given a number return another number closest to the input which has same number of 1 bits
        Solution :- Start from the end and check if last and but one last digit match if not then
         build a bitMap to reverse those 2 bits
     */
    public long closestInSameBitCount(long x){
        for (int i = 0; i < NUM_UNSIGN_BITS ; i++){
            if( ((x>>> i) & 1) !=  ((x>>> (i+1)) & 1)){
                long bitMask =(1L << i) | (1L << (i+1));
                System.out.println(Long.toBinaryString(bitMask));
                x ^= bitMask;
                return x;
            }
        }
        return -1;
    }

}

No comments:

Post a Comment