• HDU1013


    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
    ", ans);
    	}
    
    
    	return 0; 
    }
    

      

  • 相关阅读:
    SSH免密码登陆备忘
    WeiBo官网oauth2开发文档理解
    TOP
    使用定位,逆地理编码,经纬度《=转=》地址信息、逆地理编码,地址《=转=》经纬度,贼方便!!!!
    计算机病毒分类之感染目标
    预处理
    指针与引用
    printf问题参数顺序
    神奇的求平均数
    C和C++的关系
  • 原文地址:https://www.cnblogs.com/jluzhsai/p/4988064.html
Copyright © 2020-2023  润新知