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