UVa 10922 2 the 9s

我們知道要怎麼確定一個整數是不是 9 的倍數-如果它每位數的總和是9的倍數,那它就是9的倍數。這種檢驗的方法其實是一種遞迴的方法,而且我們把這種方法遞迴的深度稱作 N 的 9-degree 。

你的工作就是,給你一個正整數N,判斷他是不是9的倍數,而且如果他是9的倍數你還需要判斷它的 9-degree。

Input 

輸入含有多組測試資料。每組測試資料一列包含一個正數 N。

當 N=0 時代表輸入結束;輸入的數最大可以到1000位數。

Output 

對於每一組測試資料,請輸出它是否是 9 的倍數及它的 9-degree。輸出格式請參考Sample Output。

Sample Input 

999999999999999999999
9
9999999999999999999999999999998
837
0

Sample Output 

999999999999999999999 is a multiple of 9 and has 9-degree 3.
9 is a multiple of 9 and has 9-degree 1.
9999999999999999999999999999998 is not a multiple of 9.
837 is a multiple of 9 and has 9-degree 2.

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

int main()
{
    string s;
    while(cin >> s){
        if (s.length() == 0 || s[0] == '0'){
            break; 
        }

        int sum = 0;
        for (int i = 0; i < s.length(); i++){
            sum += s[i] - '0'; //先把所有位加起来
        }

        int dep = 0;
        int is9mul = 0;

        if (sum % 9 == 0){
            is9mul = 1; //如果一个数是9的倍数,肯定能一直递归下去
            dep = 1; //开始的时候,只要能被9整除,深度就是1;
        }

        while (sum % 9 == 0 && sum > 9){
            int temp = sum;
            sum = 0;
            while(temp){
                sum += temp % 10; 
                temp /= 10;
            }
            dep++;
        }
        cout << s << " is ";
        if (!is9mul) cout << "not ";
        cout << "a multiple of 9";
        if (dep) cout << " and has 9-degree " << dep;
        cout << "." << endl;
    }
    return 0;
}

 

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注