zoukankan      html  css  js  c++  java
  • 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; 
    }
    

      

  • 相关阅读:
    poj4474 Scout YYF I(概率dp+矩阵快速幂)
    网络编程之TCP异步群聊:服务器端代码
    平衡树(AVL)详解
    网络编程之TCP异步群聊:客户端代码
    [置顶] android 图片库的封装
    oracle的nvl函数的使用解析
    七天美音英标学习总结
    软考(7)——看图心想 标准化和知识产权
    Node.js学习(7)----包
    Ubuntu bitnami gitlab 安装
  • 原文地址:https://www.cnblogs.com/jluzhsai/p/4988064.html
Copyright © 2011-2022 走看看