阿摩線上測驗 登入

申論題資訊

試卷:108年 - 108 臺灣土地銀行新進一般金融人員及專業人員甄試:程式設計人員(一)_七職等_綜合科目:含邏輯推理(邏輯推理運算)、程式設計(C#/C++、JAVA)、資料庫管理(包括 SQL 語言)、網路管理#81796
科目:綜合科目-邏輯推理、計算機概論、程式設計(.NET、COBOL、JAVA+SQL程式語言)
年份:108年
排序:0

題組內容

第三題: 請回答下列問題:

申論題內容

(一)此問題請用 C++或 C#做答。如果一個整數變數是 32 位元,請設計一程式,讓 使用者輸入一個整數值,並且將此整數值中含有多少個二進位的「1」列印出來。 例如當使用者輸入值為「40(10)」=「00000000000000000000000000101000(2)」 時,則輸出結果為 2。【10 分】

詳解 (共 1 筆)

詳解 提供者:hchungw
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" 的數量。