方法一:公式法(n+8)%9+1;
#include <iostream> #include <cstdio> using namespace std; typedef long long ll; int main(){ ll n; while(~scanf("%lld", &n) && n){ printf("%lld\n", (n+8)%9+1); } }
方法二:数字和不超过long long范围
假设输入数字达到10^19位那么长,此时每个数位上假设取最大值9,最大和为9*10^19,而long long的最大值为9223372036854775807(19位数字),理论上完全可以容纳下输入的数字各位的累加和,故采用long long来保存结果已经足够
#include <iostream> #include <cstdio> #include <string> using namespace std; typedef long long ll; int main(){ string n; while(cin >> n && n != "0"){ string tmp = n; ll dr; while(1){ dr = 0; for(char ch : tmp){ dr += ch - '0'; } if(dr < 10) break; tmp = to_string(dr); } printf("%lld\n", dr); } return 0; }
方法三:处理超长数字输入(10^19位以上数字):高精度+低精度
#include <iostream> #include <cstdio> #include <string> #include <algorithm> using namespace std; typedef long long ll; string add(string a, char b){ reverse(a.begin(), a.end()); int la = a.length(); string c = ""; int carry = 0; for(int i = 0; i < la; i++){ int tmp = (a[i] - '0') + (b - '0') + carry; carry = tmp / 10; c = c + char((tmp % 10) + '0'); b = '0'; } if(carry != 0){ c = c + char(carry + '0'); } reverse(c.begin(),c.end()); return c; } int main(){ string n; while(cin >> n && n != "0"){ string tmp = n, dr = ""; while(1){ for(char ch : tmp){ if(dr == ""){ dr = dr + ch; continue; } dr = add(dr, ch); } if(dr.length() <= 1) break; else {tmp = dr; dr = "";} } cout << dr << endl; } return 0; }