码迷,mamicode.com
首页 > 其他好文 > 详细

HDU1013

时间:2015-11-23 13:31:41      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

 

It is a easy problem. 

But we can have two ways to solve this problem.

The first way is simulation that calculate each number repeatedly.

The second way is using numeric method that one numer mod 9 is equal to summing those digits mod 9.

Like Follow:

Because: ABCD...XYZ%9 == [ A(10^(n-1)) + B(10^(n-2)) + ... + Z ]%9

Suppose: ABCD...XYZ%9 == (A+B+C+D+...+X+Y+Z)%9

So:

ABCD...XYZ%9 - (A+B+C+D+...+X+Y+Z)%9 = 0

[ A(10^(n-1)) + B(10^(n-2)) + ... + Z ]%9 - (A+B+C+D+...+X+Y+Z)%9 = 0

 

Problem Description:

The digital root of a positive integer is found by summing the digits of the integer. If the resulting value is a single digit then that digit is the digital root. If the resulting value contains two or more digits, those digits are summed and the process is repeated. This is continued as long as necessary to obtain a single digit.

For example, consider the positive integer 24. Adding the 2 and the 4 yields a value of 6. Since 6 is a single digit, 6 is the digital root of 24. Now consider the positive integer 39. Adding the 3 and the 9 yields 12. Since 12 is not a single digit, the process must be repeated. Adding the 1 and the 2 yeilds 3, a single digit and also the digital root of 39.

For each integer in the input, output its digital root on a separate line of the output.

 

#include <iostream>
#include <string>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

using namespace std; 

int const MAXN = 1000000;

int N;



int rootStr(char *str)
{
	int addNum;
	int len; 
	
	addNum = 0; 
	len = strlen(str);	
	for(int i=0; i<len; i++)
		addNum += str[i] - ‘0‘;
	
	while(addNum > 9)
	{
		addNum = 0; 
		len = strlen(str);
		for(int i=0; i<len; i++)
			addNum += str[i] - ‘0‘;
		sprintf(str, "%d", addNum);
	}
	return addNum;
}

int rootStr2(char *str)
{
	int addNum;
	int len; 
	
	addNum = 0; 
	len = strlen(str);	
	for(int i=0; i<len; i++)
		addNum += str[i] - ‘0‘;
	
	if(addNum%9==0)
		return 9;
	else 
		return addNum%9;
}

int main()
{

#ifndef ONLINE_JUDGE
	freopen("in.txt", "r", stdin);
#endif	
	
	char a[MAXN];
	while(~scanf("%s", a) && a[0] !=‘0‘)
	{
	//	int ans = rootStr(a);
		int ans = rootStr2(a);
		printf("%d\n", ans);
	}


	return 0; 
}

  

HDU1013

标签:

原文地址:http://www.cnblogs.com/jluzhsai/p/4988064.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!