【題解】CPE 一顆星選集:26. Fibonaccimal Base

題目

cannot have two consecutive Fibonacci numbers
UVa 連結
ZeroJudge 連結

解法

先找最接近 n 的 fib,從大到小去做。

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

int main(){
    int T, n, backup, a, b, temp;
    cin >> T;
    while(T--){
        cin >> n;
        backup = n;
        vector<int> v;
        while(n > 0){
            a = 0, b = 1;
            while(b <= n){
                temp = a;
                a = b;
                b = temp + b;
            }
            v.push_back(a);
            n -= a;
        }
        string s = "";
        a = 0, b = 1;
        while(!v.empty()){
            temp = a;
            a = b;
            b = temp + b;
            if(v.back() == b){
                s += "1";
                v.pop_back();
            }else{
                s += "0";
            }
        }
        reverse(s.begin(), s.end());
        cout << backup << " = " << s << " (fib)\n";
    }
}
👉 回到:【CPE大學程式能力檢定】目錄
發佈留言

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