題目意思:讀取一數字,此數字最大有1000位。計算該數字是否為九的倍數?如是,再計算其階層數。
※判斷是否為九的倍數:所有位數相加 ÷ 9=0,即為九的倍數。
※計算階層數:所有位數相加後得出的第一個總和為一階,依此類推直到該數字無法再計算總和。
Example 1:
999 => 27(9+9+9, 1階) => 9(2+7, 2階)
Example 2:
99999 99999 99999 99999 9 => 189(9+9+...+9, 1階) => 18(1+8+9, 2階) => 9(1+8, 3階)
1 #include <cstdio> 2 using namespace std; 3 4 int main() 5 { 6 char str[1005]; 7 while(scanf("%s", str) && str[0] != '0') 8 { 9 int degree = 0, sum = 0; 10 for(int i = 0; str[i]; i++) 11 sum += str[i] - '0'; 12 degree ++; 13 if( !(sum % 9)) 14 { 15 while(sum > 9) 16 { degree ++; 17 int tempsum = 0, temp = sum; 18 while(temp) 19 { 20 tempsum += temp % 10; 21 temp /= 10; 22 } 23 sum = tempsum; 24 } 25 printf("%s is a multiple of 9 and has 9-degree %d. ", str, degree); 26 }else printf("%s is not a multiple of 9. ", str); 27 } 28 return 0; 29 }