zoukankan      html  css  js  c++  java
  • 剑指 Offer 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

    思路解析

    int sumNums(int n) {
        if(n == 0)
            return n;
        return sumNums(n - 1) + n;
    }
    

    这是正常情况下的递归写法,但是使用了if语句,需要想办法去掉if语句。

    注意逻辑运算符的短路效应:
    A && B,若Afalse,则不再计算B,直接返回false
    A || B,若Atrue,则不再计算B,直接返回true
    利用这一点,实现不通过if语句的截断。

    代码实现

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

    狗头解法

    class Solution {
    public:
        int sumNums(int n) {
            bool arr[n][n+1];
            return sizeof(arr)>>1;
        }
    };
    
  • 相关阅读:
    template(2.2)
    Filter过滤链条
    The 3n + 1 problem
    Struts2.3+Spring4.0
    康托展开
    templates(2.1)
    templates(1.2)
    templates(1.1)
    我和你
    Android 的上下文菜单: Context Menu
  • 原文地址:https://www.cnblogs.com/xqmeng/p/13681778.html
Copyright © 2011-2022 走看看