d672 - 10922 - 2 the 9s
題目描述
題目要求判斷一個給定的正整數是否為 9 的倍數,如果是,則計算其 9-degree。9-degree 定義為將數字的各位數相加,如果結果仍為 9 的倍數,則重複此過程,直到結果小於 9 為止,重複的次數即為 9-degree。
解題思路
程式碼首先讀取輸入的數字字串。如果輸入為 "0",則結束程式。對於每個輸入數字,程式會計算其各位數的總和。如果總和是 9 的倍數,則進入一個迴圈,不斷計算總和的各位數,直到總和小於 9 為止。迴圈中的每次迭代都表示 9-degree 的增加。最後,程式輸出數字是否為 9 的倍數以及其 9-degree。如果數字不是 9 的倍數,則直接輸出 "is not a multiple of 9."。
複雜度分析
- 時間複雜度: O(N*K),其中 N 是輸入數字的位數,K 是計算 9-degree 的迭代次數。在最壞情況下,K 可能與 N 成正比。
- 空間複雜度: O(N),主要用於儲存數字字串。
程式碼
#include <iostream>
#include <string>
using namespace std;
int main(){
std::ios::sync_with_stdio(false);
cin.tie(NULL);
string a;
while(cin >> a){
if(a!="0"){
cout << a;
int de=1,n=0,i;
for(i=0;i<a.length();i++)
n+=a[i]-48;
if(n%9==0){
while(n>9){
for(a.clear();n>0;n/=10)
a+=n%10+48;
for(i=0;i<a.length();i++)
n+=a[i]-48;
de++;
}
cout <<" is a multiple of 9 and has 9-degree " << de << "."<< endl;
}
else
cout <<" is not a multiple of 9.\n";
}
}
}