zoukankan      html  css  js  c++  java
  • 【剑指Offer】47求1+2+3+...+n

    题目描述

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

    时间限制:1秒;空间限制:32768K

    解题思路

    利用逻辑运算的短路特性,作为递归的终止条件。

    要注意python中逻辑运算符的用法:a and b,a为False返回a,a为True就返回b.

    Python代码:

    class Solution:
        def Sum_Solution(self, n):
            # write code here
            result = n
            a = n and self.Sum_Solution(n-1)
            result += a
            return result

    C++代码:

    class Solution {
    public:
        int Sum_Solution(int n) {
            int ans = n;
            ans && (ans += Sum_Solution(n - 1));
            return ans;
        }
    };
  • 相关阅读:
    【Golang基础总结】数组和切片的比较
    如何转载别人的文章
    C语言字节对齐问题详解
    幷查集拓展
    贪心
    dfs
    Trie
    哈夫曼树
    bfs
    并查集
  • 原文地址:https://www.cnblogs.com/yucen/p/9912015.html
Copyright © 2011-2022 走看看