熱門文章

2025年7月8日 星期二

ZeroJudge 解題筆記:a414. 位元運算之進位篇

作者:王一哲
日期:2025年7月8日


ZeroJudge 題目連結:a414. 位元運算之進位篇

解題想法


假設二進位制數字 $n$ 要加 1,其進位次數等於 $n$ 從最右側向左算共有幾個連續的 1。

Python 程式碼


使用時間約為 0.8 s,記憶體約為 65.9 MB,通過測試。這題的測資量很大,用 print 輸出會很慢,大約要 2 s。
import sys

result = []
lines = sys.stdin.readlines()
for line in lines:
    n = int(line)
    if n == 0: break
    cnt = 0
    while n&1:
        n >>= 1
        cnt += 1
    result.append(f"{cnt:d}\n")
sys.stdout.write("".join(result))


C++ 程式碼


使用時間約為 0.1 s,記憶體約為 84 kB,通過測試。
#include <cstdio>
using namespace std;

int main() {
    int n;
    while(scanf("%d", &n) != EOF && n != 0) {
        int cnt = 0;
        while(n&1) {
            n >>= 1;
            cnt++;
        }
        printf("%d\n", cnt);
    }
    return 0;
}


沒有留言:

張貼留言