2013年4月14日 星期日

10035 - Primary Arithmetic

Children are taught to add multi-digit numbers from right-to-left one digit at a time. Many find the "carry" operation - in which a 1 is carried from one digit position to be added to the next - to be a significant challenge. Your job is to count the number of carry operations for each of a set of addition problems so that educators may assess their difficulty.

Input

Each line of input contains two unsigned integers less than 10 digits. The last line of input contains 0 0.

Output

For each line of input except the last you should compute and print the number of carry operations that would result from adding the two numbers, in the format shown below.

Sample Input

123 456
555 555
123 594
0 0

Sample Output

No carry operation.
3 carry operations.
1 carry operation.

出處: UVa Online Judge - Primary Arithmetic




問題敘述

此題會給您很多成對的整數,要求您計算出將兩個整數相加所需要的進位次數。

解題思路

此題可以用取餘數和除法的方式解析出每個位數,並且作加法計算進位次數,除此之外還有要注意的是如果沒有進位或只有一個進位的話輸出operation,其他的輸出operations。

c++ 程式碼

#include <iostream>
using namespace std;

int main() {
    int numA, numB;

    while (true) {
        int carryNum = 0;
        bool isCarry = false;

        cin >> numA >> numB;
        if (!(numA || numB))
            break;
        while (numA || numB) {
            int digitA = numA % 10;
            int digitB = numB % 10;

            if (isCarry) {
                isCarry = false;
                digitA++;
            }
            if (digitA + digitB >= 10) {
                isCarry = true;
                carryNum++;
            }
            numA /= 10;
            numB /= 10;
        }
        if (!carryNum)
            cout << "No carry operation." << endl;
        else if (carryNum == 1)
            cout << "1 carry operation." << endl;
        else
            cout << carryNum << " carry operations." << endl;
    }

    return 0;
}

沒有留言:

張貼留言