天天看點

劍指offer面試題46:求1+2+...+n

求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等關鍵字及條件判斷語句(A?B:C)。

利用&&的短路效應:

#include <iostream>
using namespace std;

class Solution {
public:
     int Sum_Solution(int n) {
        int sum = ;
        n&& (sum  = n + Sum_Solution(n - ));
        return sum;
    }

};

int main()
{
    Solution s;
    cout << s.Sum_Solution() << endl;
    system("PAUSE");
    return ;
}
           

繼續閱讀