Skip to content

Instantly share code, notes, and snippets.

@okutane
Created March 30, 2017 12:49
Show Gist options
  • Save okutane/41ab43b442b7de1cc0cbc49573e497c5 to your computer and use it in GitHub Desktop.
Save okutane/41ab43b442b7de1cc0cbc49573e497c5 to your computer and use it in GitHub Desktop.
Given K = 2^a[0] + 2^a[1] + ... + 2^a[n-1] calculate number of set bits in K*3
public class BitsInK3 {
static int solution(int A[]) {
State state = new State();
for (int i : A) {
state.putBit(i);
state.putBit(i + 1);
}
return state.getResult();
}
private static class State {
int setBits = 0;
int lastSetBit = -1;
int lastBit = -1;
void putBit(int i) {
if (lastBit < i) {
lastBit = i;
lastSetBit = lastBit;
setBits++;
} else if (lastBit == i) {
lastBit++;
} else {
setBits++;
}
}
public int getResult() {
return setBits;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment