求 1+2+…+n ,要求不能使用乘除法、for、while、if、else、switch、case等關鍵字及條件判斷語句(A?B:C)。
示例 1:
輸入: n = 3
輸出: 6
示例 2:
輸入: n = 9
輸出: 45
限制:
1 <= n <= 10000
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/qiu-12n-lcof
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
解答:
1)數學公式
class Solution {
public:
int sumNums(int n) {
int ansint = n*(n+1)/2;
return ansint;
}
};
位運算短路性質
class Solution {
public:
int ans = 0;
int sumNums(int n) {
bool x= n>1&&sumNums(n-1)>0;
ans+=n;
return ans;
}
};