如何解决计算前N个自然数中的置位总数
例如,假设N = 4,则设置位的总数从1到4 = 5;
1:0001
2:0010
3:0011
4:0100
这是一种log(n)
算法。
public static int countSetBits(int n){
n++;
int count = n / 2;
int power = 2;
while(power <= n) {
int totalPairs = n / power;
count += (totalPairs / 2) * power;
// if count of totalPairs was odd,then count
// remaining 1s which could not be grouped together
count += (totalPairs % 2 == 1) ? (n % power) : 0;
power <<= 1;
}
return count;
}
为什么我们要在输入值上加1?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。