利用字串儲存數字,然後把每一位數字相加,相加完轉回字串,再做一次每位數字相加,一直重複這樣的動作到只剩一位數再去判斷是否為9的倍數即可。
P.S. 不管原本數字是多少位數,都至少要做一次,也就是說degree至少是1。
C++(0.070)
/*******************************************************/
/* UVa 10922 2 the 9s */
/* Author: Maplewing [at] knightzone.studio */
/* Version: 2015/07/19 */
/*******************************************************/
#include <iostream>
#include <sstream>
#include <cstdio>
#include <string>
using namespace std;
string toString(int num){
stringstream ss;
ss << num;
return ss.str();
}
int main(){
string num;
while( getline(cin, num) && num != "0"){
string temp = num;
int degree = (num.length() == 1)? 1 : 0;
while( temp.length() > 1 ){
int number = 0;
for( int i = 0 ; i < temp.length() ; ++i ){
number += temp[i] - '0';
}
temp = toString(number);
++degree;
}
if( (temp[0] - '0') % 9 == 0 ){
printf("%s is a multiple of 9 and has 9-degree %d.\n", num.c_str(), degree);
}
else {
printf("%s is not a multiple of 9.\n", num.c_str());
}
}
return 0;
}