统计二进制数中1的个数
与2^i进行与运算
public class Solution {
public int hammingWeight(int n) {
int ret = 0;
while (n != 0) {
n &= n - 1;
ret++;
}
return ret;
}
}
统计字符串中最小字符的出现次数
public int f(String s) {
int cnt = 0;
char ch = 'z';
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c < ch) {
ch = c;
cnt = 1;
} else if (c == ch) {
cnt++;
}
}
return cnt;
}