ZOJ Problem Set - 1115

来源:互联网 发布:前端怎么获取数据 编辑:程序博客网 时间:2024/04/28 06:40

ZOJ Problem Set - 1115

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=115

 

如果不用字符处理方式来得出第一次位数和的话会超时。

 

#include <iostream>
#include <string>

using namespace std;

int getNum(string s) {
    int sSum = 0;
    for(int i = 0;i < s.size();i++)
        sSum += s[i] - '0';
    return sSum;
}

int nSum(int n) {
    if(10 > n) return n;
    int sum;
    while(0 == sum || 9 < sum) {
        sum = 0;
        while(0 < n) {
            sum += n % 10;
            n = n / 10;
        }
        n = sum;
    }
    return sum;
}

int main()
{
    string str;
    int num;
    while(1) {
        cin >> str;
        if("0" == str) break;
        num = getNum(str);
        while(9 < num) {
            num = nSum(num);
        }
        cout << num << endl;
    }
    return 0;
}

 

原创粉丝点击