熱門文章

2025年12月20日 星期六

ZeroJudge 解題筆記:a132. 10931 - Parity

作者:王一哲
日期:2025年12月20日


ZeroJudge 題目連結:a132. 10931 - Parity

解題想法


這題要將一個 10 進位整數轉換成 2 進位字串,再計算字串中 1 的數量。如果用 Python 解題,可以直接用內建的 bin,不過轉換後的字串前面有 0b,要用切片從索引值 2 開始取子字串。如果用 C++ 解題,可以自己寫轉換用的函式,也可以引入 bitset,用 bitset 之中的 to_string() 功能轉換整數。

Python 程式碼


Python 有內建的 10 進位整數轉換成 2 進位字串函式,使用時間約為 8 ms,記憶體約為 2.9 MB,通過測試。
import sys

for line in sys.stdin:
    n = int(line)
    if n == 0: break
    s = bin(n)[2:]
    p = sum([c == '1' for c in s])
    print(f"The parity of {s:s} is {p:d} (mod 2).")


C++ 程式碼


自己寫將 10 進位整數轉換成 2 進位字串的函式,使用時間約為 1 ms,記憶體約為 316 kB,通過測試。
#include <iostream>
#include <string>
using namespace std;

string bin(int n) {
    string s = "";
    while(n) {
        if (n&1) s = "1" + s;
        else s = "0" + s;
        n >>= 1;
    }
    return s;
}

int main() {
    ios::sync_with_stdio(0); cin.tie(0);
    int n;
    while(cin >> n && n != 0) {
        string s = bin(n);
        int p = 0;
        for(char c : s) {
            if (c == '1') p++;
        }
        cout << "The parity of " << s << " is " << p << " (mod 2).\n";
    }
    return 0;
}

用 bitset 轉換 2 進位字串的功能,使用時間約為 2 ms,記憶體約為 316 kB,通過測試。
#include <iostream>
#include <bitset>
using namespace std;

int main() {
    ios::sync_with_stdio(0); cin.tie(0);
    int n;
    while(cin >> n && n != 0) {
        bitset<32> b (n);
        string bin_str = b.to_string();
        auto first_digit = bin_str.find('1');
        cout << "The parity of " << bin_str.substr(first_digit) << " is " << b.count() << " (mod 2).\n";
    }
    return 0;
}


沒有留言:

張貼留言