置頂

我的 VPython 教學文件 (HackMD 版本)

VPython 教學文件目錄 安裝及測試 基本語法 等速度直線運動 自由落下 終端速度 水平抛射 使用For迴圈計算水平抛射資料 斜向抛射 圓周運動 簡諧運動 單擺 木塊彈簧系統分離 重力及簡諧 行星運動 相疊木塊 雙重簡諧運動 一維彈性碰撞 ...

熱門文章

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;
}


沒有留言:

張貼留言