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; 
    }
    

      

  • 相关阅读:
    Centos 卸载 MySQL
    Kafka体系架构、命令、Go案例
    Go 平滑重启(优雅重启)
    etcd集群数据迁移至新集群
    ubuntu 20.04使用TLSv1
    mybatis拦截器对SQL处理,数据权限逻辑控制
    java敏感字查找和替换
    SpringBoot自定义validation验证
    java使用druid解析器解析SQL语句
    国产数据库人大金仓 KingbaseES V8 R2 在 x86_64 Linux 安装过程
  • 原文地址:https://www.cnblogs.com/jluzhsai/p/4988064.html
Copyright © 2011-2022 走看看