a494中等長整數字串與9-degree

CPE:2 the 9s (UVa 10922)

不解析千位整數,判斷9的倍數並追蹤數字和層數。

前往題目練習 →回報教學錯誤時間 O(L),空間 O(L)保存原字串,L≤1000。

解題思路

N最多1000位,因此保留原始字串並先把各字元數字加總,總和最多9000。因N與數字和模9相同,若此和不被9整除,直接輸出不是倍數;否則反覆計算這個小整數的數字和直到9。

第一輪由原字串算數字和就計為degree=1,之後每替換一次再加1。特別N=9時第一輪仍得到9,degree維持1,符合題目的特殊定義。輸出必須用原字串而不是其數字和,保留完整英文及句點;單獨的0結束。

Step-by-step animation

示意:N=999999999

回報動畫錯誤
步驟 1 / 3

第一層

九個9的數字和為81。

9×9
81
degree
1
sum
81

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <string>
using namespace std;
int main() {
    string s;
    while (cin >> s && s != "0") {
        int sum = 0;
        for (char c : s)
            sum += c - '0';
        if (sum % 9)
            cout << s << " is not a multiple of 9.\n";
        else {
            int degree = 1;
            while (sum > 9) {
                int next = 0;
                while (sum) {
                    next += sum % 10;
                    sum /= 10;
                }
                sum = next;
                ++degree;
            }
            cout << s << " is a multiple of 9 and has 9-degree " << degree << ".\n";
        }
    }
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多