Skip to content

Instantly share code, notes, and snippets.

@sreeprasad
Created September 5, 2019 12:46
Show Gist options
  • Save sreeprasad/606a8146263ce26976e8ca7b9aae5f0c to your computer and use it in GitHub Desktop.
Save sreeprasad/606a8146263ce26976e8ca7b9aae5f0c to your computer and use it in GitHub Desktop.
public int minValue(int N) {
if(N==0) return 1;
if((N&N-1)==0) return 1;
int x = Integer.bitCount(N);
int count=0; // is the number of bit set in N
int t = N;
while(t>0){
t>>=1;
count++;
}
int nextHighestPowerOfTwo = 1<<count;
int diff = nextHighestPowerOfTwo-N;
int y = Integer.bitCount(diff)+1;
return Math.min(x,y);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment