題目
解法一:字串拆解
#include <iostream>
using namespace std;
int f(int n){
if(n <= 9) return n;
return f(stoi(to_string(n).substr(0, 1)) + f(stoi(to_string(n).substr(1))));
}
int main(){
int n;
while(cin >> n && n){
cout << f(n) << endl;
}
}解法二:取尾數
#include <iostream>
using namespace std;
int f(int n){
int ans = 0;
while(n > 0){
ans += n % 10;
n /= 10;
}
if(ans <= 9) return ans;
return f(ans);
}
int main(){
int n;
while(cin >> n && n){
cout << f(n) << endl;
}
}👉 回到:【CPE大學程式能力檢定】目錄