---
# System prepended metadata

title: 2 the 9s(UVA10922)
tags: [CPE一顆星必考題]

---

# 2 the 9s(UVA10922)
## [程式繳交區](https://hackmd.io/@Renektonn/rJtEHJTukg/edit)
## 題目
[點我](https://onlinejudge.org/external/109/10922.pdf)

## 解題網站
[UVA](https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1863)
[ZJ](https://zerojudge.tw/ShowProblem?problemid=d672)

## 演算法
```
1. 輸入字串str，若str為"0"，則停止
2. 將str遞迴加總，直到變為個位數，計算過程中加了幾次
3. 根據回傳值，輸出對應的格式

9 is a multiple of 9 and has 9-degree 1.
9999999999999999999999999999998 is not a multiple of 9.
```
```
digitCount(str, cnt)
1. 將str加總，存到sum中，cnt++
2. 若sum的位數是一位，
    判斷sum是否為9，若為9，回傳cnt，否則，回傳0
3. 否則，回傳digitCount(to_string(sum), cnt)

```

## 程式碼
```cpp=
#include <bits/stdc++.h>
using namespace std;

int digitCount (string str, int cnt) {
    int sum = 0;
    for (int i = 0; i < str.length(); i++) {
        sum += str[i] - '0';
    }
    cnt++;
    if (sum / 10 == 0) {
        if (sum == 9) return cnt;
        else return 0;
    } else {
        return digitCount(to_string(sum), cnt);
    }
}

int main() {
    string str;
    while (cin >> str) {
        string copyStr = str;
        if (str == "0") break;
        int cnt = digitCount(copyStr, 0);
        if (cnt != 0) {
            cout << str << " is a multiple of 9 and has 9-degree " << cnt << "." << endl;
        } else {
            cout << str << " is not a multiple of 9." << endl;
        }
    }

    return 0;
}
```