C++ 版本
#include <iostream>
int countBits(int n) {
int count = 0;
while (n) {
count += n & 1;
n >>= 1;
}
return count;
}
int main() {
int number;
std::cout << "請輸入一個整數值: ";
std::cin >> number;
int bitCount = countBits(number);
std::cout << "此整數值中含有 " << bitCount << " 個二進位的「1」." << std::endl;
return 0;
}
C# 版本
using System;
class Program
{
static int CountBits(int n)
{
int count = 0;
while (n != 0)
{
count += n & 1;
n >>= 1;
}
return count;
}
static void Main()
{
Console.Write("請輸入一個整數值: ");
int number = int.Parse(Console.ReadLine());
int bitCount = CountBits(number);
Console.WriteLine($"此整數值中含有 {bitCount} 個二進位的「1」.");
}
}
程式解釋
countBits 函式:
此函式接受一個整數並計算其二進位表示中 "1" 的數量。
使用 & 1 運算符來檢查最低位是否為 "1"。
使用右移運算符 >>= 1 將數字右移一位。
重複此過程直到數字變為 0。
主程式:
請使用者輸入一個整數值。
調用 countBits 函式計算其中 "1" 的數量。
輸出結果。
這兩個版本的程式碼均會讀取使用者輸入的整數,並計算和列印其二進位表示中 "1" 的數量。