Digital Roots 杭电1013

一道acm水题做得和尼玛一坨屎一样,真尼玛去shi算求了!!

开始一直忽略了一个问题,这尼玛N可以是无限大的啊!!

第一遍:打算用stl来做加个递归,shi一样的代码。报错:Runtime Error (STACK_OVERFLOW)

#include <cstdio>
#include <iostream>
#include <string>
#include <string.h>
using namespace std;

int digital (const string &);
const int MAX_N = 1000000;

int main ()
{
    int N;
    char buf[MAX_N];
    memset(buf, 0, MAX_N);
    while (cin >> N && N != 0)
    {
        sprintf (buf, "%d", N);
        string digits(buf);
        digital (digits);
    }
    return 0;
}

int digital (const string &digits)
{
    string str = digits;
    int sum = 0;
    char buf[MAX_N];
    memset (buf, 0, MAX_N);
    for (int i = 0; i < str.size(); i++)
    {
        sum += str[i] - '0';
    
    }
    if (sum / 10 == 0)
    {
      cout << sum << endl;
      return 0;
    }
    else
    {
        sprintf (buf, "%d", sum);
        string word(buf);
        digital(word);
    }
}

第二遍:直接用的递归,结果尼玛报错,哎,N是无限大的啊,报错:Out Of Contest Time

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

int digital ( int );

int main ()
{
    int N;
    while (cin >> N && N != 0)
    {
        digital (N);
    }
    return 0;
}

int digital ( int N)
{
    int sum = 0, n = 0;
    if (N / 10 == 0)
    {
      cout << N << endl;
      return 0;
    }
    else
    {
        while (N > 0)
        {
            n = N % 10;
            sum += n;
            N = N / 10;
        }
        digital (sum);
    }
}

第三遍:别人提醒了下,恍然大悟,ac,我在想我尼玛这脑袋是不是有点傻啊!人艰不拆啊!再不下点功夫,这尼玛真的要废了,My泪滴嘎嘎!!!

#include <iostream>
using namespace std;

int main ()
{
	string digit;
	while (cin >> digit)
	{
		int sum = 0;
		for (int i = 0; i < digit.size(); i++)
		{
			sum += digit[i] - '0';
			if (sum > 9)
			  sum = sum / 10 + sum % 10;
		}
		if (sum == 0)
		  break;
		cout << sum << endl;
	}
	return 0;
}



你可能感兴趣的:(杭电,digital,Roots,1013)