【剑指Offer】求1+2+3+...+n 解题报告(C++)

【剑指Offer】求1+2+3+…+n 解题报告(C++)

标签(空格分隔): 剑指Offer


题目地址:https://www.nowcoder.com/ta/coding-interviews

题目描述:

求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。

解题方法

题目一堆限制,就是让我们开拓思路的,没有固定解法。

这个题让我学习到了短路特性的概念。

条件1 && 条件2 条件1为假时不会执行条件2

条件1 || 条件2 条件1为真时不会执行条件2

上述即为逻辑运算符的短路特性

所以下面的代码相当于:

if(ans){
    ans += sum _Solution(ans-1);
}else
    return 0;

为什么要用C++写呢?因为Python版本的我不会。。

代码:

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

Date

2018 年 3 月 26 日 – 学车要早起,困= =

posted @ 2018-03-26 20:09  负雪明烛  阅读(62)  评论(0)    收藏  举报