10458:2 the 9s C++ 代码实现

笔者闲暇时,会找一些题目练练脑筋。本文是10458:2 the 9s的C++代码实现。

题目如下:

Introduction to the problem

A well-known trick to know if an integer N is a multiple of nine is to compute the sum S of its digits. If S is a multiple of nine, then so is N. This is a recursive test, and the depth of the recursion needed to obtain the answer on N is called the 9-degree of N.

Your job is, given a positive number N, determine if it is a multiple of nine and,if it is, its 9-degree.

Description of the input

The input is a file such that each line contains a positive number. A line containing the number 0 is the end of the input. The given numbers can contain up to 1000 digits.

Description of the output

The output of the program shall indicate, for each input number, if it is a multiple of nine, and in case it is, the value of its nine-degree. See the sample output for an example of the expected formatting of the output.

Sample input:

999999999999999999999
9
9999999999999999999999999999998
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.

 

#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
    string line;
    string originstr;
    int count = 0;
    int sum = 0;
    while (true)
    {
        count = 0;
        cin>>line;
        originstr = line;
        if (line == "0")
        {
            return 0;
        }
        while (true)
        {
            sum = 0;
            for (int i=0;i<line.size();i++)
            {
                sum += int(line.at(i)) - '0';
            }
            count++;
            if (sum%9 != 0)
            {
                cout<<originstr<<" is not a multiple of 9."<<endl;
                break;
            }else if (sum == 9)
            {
                cout<<originstr<<" is a multiple of 9 and has 9-degree "<<count<<"."<<endl;
                break;
            }
            stringstream str;
            str<<sum;
            str>>line;
            
        }


    }
}

最后吐槽一句,用惯了Python,真不习惯C++的强类型。

posted @ 2014-05-24 22:10  好又多牛肉  阅读(397)  评论(0)    收藏  举报