1551. Digital Roots
来源:互联网 发布:智能手环 数据接口 编辑:程序博客网 时间:2024/06/05 21:57
Background
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.
Input
The input file will contain a list of positive integers, one per line. The end of the input will be indicated by an integer value of zero.
Output
For each integer in the input, output its digital root on a separate line of the output.
Example
Input
24390Output
63
水题,但是刚开始考虑的很简单,没有考虑到输入的整数可能无限大的情况,所以wa了很多次,刚开始的代码是这样的:
#include<iostream>using namespace std;int f(int n){int r=0;while(n){r=r+n%10;n=n/10;}return r;}int main(){int n,d,r;while(cin>>n&&n){while(n>9){n=f(n);}cout<<n<<endl;}return 0;}改进后的代码是这样的:#include<iostream>#include<string>using namespace std;int main(){int n,d,r,l;string s;while(cin>>s&&s!="0"){r=0;for(int i=0;i<s.length();i++){r=r+s[i]-'0';if(r>9){r=r%10+r/10;}}cout<<r<<endl;}return 0;}
- 1551. Digital Roots
- Digital Roots
- Digital Roots
- Digital Roots
- Digital Roots
- Digital Roots
- Digital Roots
- Digital Roots
- Digital Roots
- Digital Roots
- Digital Roots
- Digital Roots
- Digital Roots
- Digital Roots
- Digital Roots
- Digital Roots
- Digital Roots
- Digital Roots
- 设计模式——工厂模式(Factory)
- Git远程基本操作命令
- cocos2dx游戏源码之《德州扑克》
- iOS应用截图
- Layout_weight这个属性
- 1551. Digital Roots
- Android Launcher分析和修改10——HotSeat深入进阶
- JSP简单学习01
- getDimension,getDimensionPixelOffset和getDimensionPixelSize的一点说明
- 傅里叶变换库FFTW的安装配置(VS2010)
- hdu4619 / 最大独立集
- 如何做一个让开发人员看得起的测试人员
- PrimeFaces布局技巧之二
- BroadcastReceiver应用详解(广播的应用)