题目地址:
https://www.acwing.com/problem/content/description/80/
求 1 + 2 + … + n 1+2+…+n 1+2+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
代码如下:
class Solution {
public:
int getSum(int n) {
int res = n;
// 短路与
n > 0 && (res += getSum(n - 1));
return res;
}
};
时空复杂度 O ( n ) O(n) O(n)。