#include<iostream>
#include<string>
using namespace std;
int main(){
int size = 0, a;
string str, n;
while(cin>>n){ //數字太大用string輸入
if(n=="0") break;
str = n;
if(n=="9") cout << n << " is a multiple of 9 and has 9-degree " << 1 << "." << endl; //為9就不用計算
else {
while (str.length() > 1) { //str在過程中會越變越小當位數為一時,代表計算完成
a = 0;
for (int i = 0; i < str.length(); i++) {
a = a + str[i] - '0'; //將每個位數轉int相加
}
size++; //計算9-degree
str = to_string(a);
}
if (str == "9") cout << n << " is a multiple of 9 and has 9-degree " << size << "." << endl;
else cout << n << " is not a multiple of 9." << endl;
}
size = 0;
}
}
1.當總和大於9時會重複跑回圈,直到小於9時停止
2.輸入以字串型態存取,基於ASCII碼扣除'0'轉為數字家加法
#include <iostream>
#include <sstream>
using namespace std;
int main(){
string s="";
int sum=0;
stringstream ss;
while(cin>>s&&s!="0"){
ss.str("");
do{
ss.str("");
sum=0;
for(int i=0;i<s.length();i++){
sum+=s[i]-'0';
}
ss<<sum;
s=ss.str();
}while(sum>9);
cout<<sum<<endl;
sum=0;
}
}
點我進UVA10050
此題有參考過網路大神解法!
#include<iostream>
using namespace std;
int main(){
int t,day,p,h[100];
cin>>t;
while(t--){
cin>>day>>p;
for(int i=0;i<p;i++){
cin>>h[i];
}
int hartal=0;//罷會的天數
for(int i=1;i<=day;i++){
if(i%7==6){//因為是從星期天當第一天,若餘六就代表該天是星期五
i++; //加一後該天為星期六
continue;//而星期五跟六都不會罷會,所以遇到就直接跳過
}
for(int j=0;j<p;j++){
if(i%h[j]==0){
hartal++;
break;//因為若多個政黨都在同一天罷會的話,只需算一天,
//所以有遇到哪個政黨罷會就直接hartal++並break避免重複算
}
}
}
cout<<hartal<<endl;
}
return 0;
}