剑指 Offer 64 求1+2+…+n

标签: 剑指 Offer 发布于:2022-02-28 10:35:54 编辑于:2022-02-28 10:35:54 浏览量:876

概述

https://leetcode-cn.com/problems/qiu-12n-lcof/

不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)

那我们可以位运算和加减。

不能条件判断意味着递归的 base case 没办法写了,我们又不能循环。


绝绝子,看了《剑指 Offer》,大体有:

  1. 借助构造函数来模拟循环,
  2. 利用虚函数来模拟递归,
  3. 利用函数指针来模拟递归,
  4. 利用模板类型来完成递归,

函数指针求解

由于 reference to non-static function must be called,我们不得不修改给定函数的声明,给其加上 static

class Solution {
public:
    typedef int (*fun)(int);
    static int terminator(int n) {
        return 0;
    }

    static int sumNums(int n) {
        fun f[2] = {terminator, sumNums};
        return n + f[bool(n)](n - 1);
    }
};

未经允许,禁止转载,本文源站链接:https://iamazing.cn/