ZeroJudge C014: Primary Arithmetic

題目敘述

本題採EOF方式收資料,每筆資料只有一行有兩個正整數a和b,當a和b都是0時代表測資結束停止收資料,a和b均小於10位數。要求輸出進行a+b的計算時總共進位了多少次 (輸出格式請見範例輸出)。


範例輸入 #1

123 456

555 555

123 594

0 0

範例輸出 #1

No carry operation.

3 carry operations.

1 carry operation.


解題思路

使用字串收數字,然後用最傳統的直式來做計算,可以先將兩個字串做反轉這樣跑For迴圈的時候可以從左跑到右。

解題程式碼如下 (僅供參考):

#include <iostream>
#include <algorithm>
using namespace std;

int toint(char a)
{
    return int(a - '0');
}

void output(int ans)
{
    if (ans == 0) cout << "No carry operation.\n";
    else if (ans == 1) cout << "1 carry operation.\n";
    else cout << ans << " carry operations.\n";
}

int main() {
    cin.sync_with_stdio(false);
    cin.tie(nullptr);
    int a, b;
    while (cin >> a >> b)
    {
        if (a == 0 && b == 0) break;
        else
        {
            if (a > b) swap(a, b);
            int count = 0;
            string one = to_string(a);
            string two = to_string(b);
            reverse(one.begin(), one.end());
            reverse(two.begin(), two.end());
            int carry = 0, ans = 0;
            for (int i = 0; i<max(one.length(), two.length()); i++)
            {
                int sum = carry;
                if(i < (int) one.size()) {
                    sum += one[i] - '0';
                }
                if(i < (int) two.size()) {
                    sum += two[i] - '0';
                }
                carry = (sum >= 10);
                ans += carry;
            }
            output(ans);
        }
    }
}

留言

這個網誌中的熱門文章

ZeroJudge M933: 邏輯電路

ZeroJudge A148: You Cannot Pass?!

ZeroJudge M932: 蜜蜂觀察