面试题64. 求1+2+…+n. 条件判断

求 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.条件判断
不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
使用逻辑符号代替条件判断语句

class Solution {
public:
    int ans = 0;
    int sumNums(int n) {
        bool x = n > 1 && sumNums(n - 1);
        ans += n;
        return ans;
    }
};
posted @ 2020-06-02 01:40  _西瓜不甜  阅读(88)  评论(0编辑  收藏  举报