Created
March 30, 2017 12:49
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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