今天來解YKL21(UVA10922):2 the 9s
主要是判斷輸入是不是9的倍數
如果是的話,再計算 9-degree
EX:
input 999999999999999999999
1.計算所有位數的和: 9+9+...9+9 = 189
2.189還不是個位數,所以繼續: 1+8+9 = 18
3.18也還不是個位數,1+8 = 9
4.最後9是個位數,進行了3次遞迴計算
5.輸出 3
#include <iostream>
#include <string>
using namespace std;
int nineDegree(int sum) {
int degree = 1;
while (sum >= 10) {
int degree_sum = 0;
while (sum > 0) {
degree_sum += sum % 10;
sum /= 10;
}
sum = degree_sum;
degree++;
}
return degree;
}
int main(){
string str;
while(cin >> str){
int sum=0;
if(str=="0")break;
for(int i=0;i<str.size();i++){
sum+=str[i] - '0';
}
if(sum%9==0){
int count =0;
int N = nineDegree(sum);
cout << str << " is a multiple of 9 and has 9-degree " << N << "." << endl;
}else{
cout << str << " is not a multiple of 9." << endl;
}
}
return 0;
}