【題解】CPE 一顆星選集:10. Summing Digits

題目

UVa 連結
ZeroJudge 連結

解法一:字串拆解

#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大學程式能力檢定】目錄
發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *