熱門文章

2025年5月14日 星期三

ZeroJudge 解題筆記:k924. P1. 數字結合 (Combination)

作者:王一哲
日期:2025年5月14日



ZeroJudge 題目連結:k924. P1. 數字結合 (Combination)

解題想法


先將兩個字串合併,再計算奇數位數和、偶數位數和,如果兩者的差是 11 的倍數印出 Yes,反之印出 No。

Python 程式碼


使用時間約為 26 ms,記憶體約為 3.3 MB,通過測試。
import sys

for line in sys.stdin:
    s = "".join(line.split())  # 兩個整數合併
    odd, even = 0, 0  # 奇數位數和,偶數位數和
    for i, c in enumerate(s):  # 計算奇數位數和、偶數位數和
        if i%2 == 1: odd += int(c)
        else: even += int(c)
    dif = abs(odd - even)
    print("Yes" if dif%11 == 0 else "No")


C++ 程式碼


使用時間約為 2 ms,記憶體約為 348 kB,通過測試。
#include <iostream>
#include <string>
#include <cstdlib>  // for abs
using namespace std;

int main() {
    ios::sync_with_stdio(0); cin.tie(0);
    string x, y;  // 兩個整數
    while(cin >> x >> y) {
        string s = x+y;
        int odd = 0, even = 0;  // 奇數位數和,偶數位數和
        for(int i=0; i<(int)s.size(); i++) {  // 計算奇數位數和、偶數位數和
            int c = s[i] - '0';
            if (i%2 == 1) odd += c;
            else even += c;
        }
        int dif = abs(odd - even);
        if (dif%11 == 0) printf("Yes\n");
        else printf("No\n");
    }
    return 0;
}


沒有留言:

張貼留言