ZeroJudge D235: You can say 11

題目敘述

題目採EOF方式收資料,每筆資料有一個正整數N (N最大可達1000位數),當N=0時停止收資料。要求輸出N是否為11的倍數 (輸出格式請見範例輸出)。


範例輸入 #1

112233

30800

2937

323455693

5038297

112234

0

範例輸出 #1

112233 is a multiple of 11.

30800 is a multiple of 11.

2937 is a multiple of 11.

323455693 is a multiple of 11.

5038297 is a multiple of 11.

112234 is not a multiple of 11.


解題思路

本題的數字會超過long long int的範圍,所以要使用字串的方式將N收進來。可以使用以下公式來判斷N是否為11的倍數:如果奇數位數的數字和與偶數位數的數字和的差是11的倍數的會N即為11的倍數。可以使用For迴圈將每一個位數的數字都做相加並在For迴圈結束後進行判斷。

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

#include <iostream>
using namespace std;

int main() {
    string str;
    while (cin >> str && str != "0")
    {
        int odd = 0, even = 0;
        for (int i = 0; i<str.length(); i++)
        {
            if (i % 2 == 0) even += int(str[i] - '0');
            else odd += int(str[i] - '0');
        }
        if ((odd - even) % 11 == 0) cout << str << " is a multiple of 11.\n";
        else cout << str << " is not a multiple of 11.\n";
    }
}

留言

這個網誌中的熱門文章

ZeroJudge M933: 邏輯電路

ZeroJudge A148: You Cannot Pass?!

ZeroJudge A263: 日期差幾天