歡迎加入我的 Discord 群組與我討論程式相關的問題!

Posted on 

 by 

 in ,

CSES – Weird Algorithm

評分:1 分,滿分為 5。

題目連結

題意

給一個數字 n ,如果 n 是奇數就把 n * 3 + 1,如果是偶入就除以 2。把過程印出來。

解題想法

用迴圈模擬就可以了!

#include <bits/stdc++.h>
using namespace std;
 
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    long long n;
    cin >> n;
    vector <long long> ans;
    ans.push_back(n);
    while(n != 1){
        if(n % 2 == 0) {
	    n /= 2;
	    ans.push_back(n);
	} else {
	    n = n*3+1;
	    ans.push_back(n);
	}
    }
    for(int i = 0;i < ans.size();i++){
	cout << ans[i] << " \n"[i == ans.size()-1];

    }

}

發表迴響

Blog at WordPress.com.

%d 位部落客按了讚: