// Some code
class CombinationIterator {
char[] current;
String orignalStr;
boolean hasNext;
public CombinationIterator(String characters, int combinationLength) {
this.current = characters.substring(0,combinationLength).toCharArray();
this.originalStr = characters;
hasNext = true; // 注意CART
}
public String next(){
if (!hasNext) {
return "";
}
String result = new String(current);
int i = current.length - 1;
int j = originalStr.length() - 1;
while (i >= 0 && current[i] == originalStr.charAt(j)) {
i--;
j--;
}
if (i == -1) {
hasNext = false; // 没办法变化了
} else {
int index = priginalStr.indexOf(current[i]);
for (int k = i; k < current.length; k++) {
index++;
current[k] = originalStr.charAt(index);
}
}
return result;
}
public boolean hasNext(){
return this.hasNext;
}
}
// Some code
class CombinationIterator {
private int combinationLength;
private String originalStr;
private int totalLength;
private int minBitmask;
private int bitmask; //current
private boolean foundNext;
public CombinationIterator(String characters, int combinationLength) {
this.orginalStr = character;
this.combinationLength = combinationLength;
this.totalLength = characters.length();
this.bitmask = (1 << totalLength) - (1 << (totalLength - combinationLength));
this.foundNext = true;
this.minBitmask = (1 << comibinationLength) - 1;
}
public String next(){
if (!hasNext()) {
return "";
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < totalLength; i++) {
if ((bitmask & (1 << totalLength - 1 - i) != 0)) {
sb.append(originalStr.charAt(i));
}
}
foundNext = false;
return sb.toString();
}
public boolean hasNext(){
if (foundNext) {
return true;
}
if (bitmask < minBitmask) {
return false;
}
bitmask --;
while (bitmask >= minBitmask && Integer.bitCount(bitmask) != combinationLength) {
bitmask--;
}
foundNext = bitmask >= minBitmask;
return foundNext;
}
}
// Some code
int count = 0;
while (n != 0) {
count += (n & 1);
n >>> 1;
}
return count;
// Some code
int count = 0;
while (n! = 0) {
n = n & (n - 1);
count++;
}
return count;
// Some code
public int hammingDistance(int x, int y) {
int number = x ^ y;
int count = 0;
while (number != 0) {
number = number & (number - 1);
count++;
}
return distance;
}