# UVA 11332 Summing Digits ## 題目連結 [UVA 11332](https://vjudge.net/problem/UVA-11332) ### 題目內容 For a positive integer n, let f(n) denote the sum of the digits of n when represented in base 10. It is easy to see that the sequence of numbers n, f(n), f(f(n)), f(f(f(n))), . . . eventually becomes a single digit number that repeats forever. Let this single digit be denoted g(n). For example, consider n = 1234567892. Then: f(n) = 1+2+3+4+5+6+7+8+9+2 = 47 f(f(n)) = 4 + 7 = 11 f(f(f(n))) = 1 + 1 = 2 Therefore, g(1234567892) = 2 ### 輸入限制 Each line of input contains a single positive integer n at most 2,000,000,000. Input is terminated by n = 0 which should not be processed. ### 輸出限制 For each such integer, you are to output a single line containing g(n). ### 解題思路 將數字當陣列算到長度為1為止。 ### 程式碼 ```cpp= #include<bits/stdc++.h> using namespace std; int main(){ string n; while(cin>>n && n!="0"){ long long ans=0; while(n.length()!=1){ ans=0; for(int i=0;i<n.length();i++){ ans+=n[i]-'0'; } n=to_string(ans); } cout<<n<<endl; } } ``` ## 測資 ### Sample input 2 11 47 1234567892 0 ### Sample output 2 2 2 2 ## 中文題目連結 [zerojudge c813](https://zerojudge.tw/ShowProblem?problemid=c813)