C# 程序用来计算数字中总的设置位
我们示例中的数字是 11,即二进制 −
1101
在 1101 中,总设置位数为 3;要找出这一数值,需创建一个循环,直至它不等于 0。此处,我们的数字为 11,即十进制 −
while (num>0) {
cal += num & 1;
num >>= 1;
}示例
要计算数字中的总设置位,请使用以下代码。
using System;
public class Demo {
public static void Main() {
int cal = 0;
// Binary is 1011
int num = 11;
while (num>0) {
cal += num & 1;
num >>= 1;
}
// 1 bits in 1101 are 3
Console.WriteLine("Total bits: "+cal);
}
}输出
Total bits: 3
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP