2021年11月30日 星期二

[ZJ e156] 良心題: 求和

原題: e156. 良心題: 求和 - 高中生程式解題系統 (zerojudge.tw)


如何不用乘法、除法、<<、>>、~、^,也不用for、while、if、else、switch、case及三元運算子,算出1+2+3+...+n ?


解題方向:


我覺得這一題滿有趣的,分享一些解法,不同寫法用到的語法細節都有點不一樣


解法如下

解 1 : 利用 new 會呼叫建構式來實現類似 for 迴圈的結構

用 new A[N] ,來呼叫 N 次 A 的建構式,再利用變數控制加總即可。


#include <bits/stdc++.h>
using namespace std;

class A {
public:
    A() {
        sum+=cnt++;
    }
    inline static int cnt = 1;
    inline static int sum = 0;
};


int main() {
    int N;
    scanf("%d", &N);
    delete [] new A[N];
    printf("%d\n", A::sum);
}


解 2 : 利用 && 會短路 (shortcut) 的特性來實現 if


#include <bits/stdc++.h>
using namespace std;

int sum(int x) {
    x && (x+=sum(x-1));
    return x;
}

int main() {
    int N;
    scanf("%d", &N);
    printf("%d\n", sum(N));
}


解 3 : 其實用 STL ,加上 algorithm 的函數就兜得出來了


#include <bits/stdc++.h>
using namespace std;
using ll = long long;

int main() {
    int N;
    scanf("%d", &N);

    vector<int> v(N);
    iota(v.begin(), v.end(), 1);
    printf("%d\n", accumulate(v.begin(), v.end(), 0));
}

沒有留言:

張貼留言