【LeetCode & 剑指offer刷题】发散思维题4:64 求1+2+…+n

【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

64 求1+2+...+n

题目描述

求1+2+3+...+n,要求不能使用乘除法for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
 
/*
方法一:利用函数指针
!!n选择函数return来终止递归
*/
/*
联系
typedef struct
{
    double real;
    double imag;
}COMPLEX;
*/
typedef  int (*fun)(int); //定义函数指针类型,方便使用
class Solution
{
public:
    static int Sum_Solution(int n)
    {
        static fun f[2] = {solution_teminator, Sum_Solution};//静态全局变量只会被初始化一次
        return n + f[!!n](n-1); //n为非0时,!!n=1, n=0时,!!n=0;n = 0时执行solution_teminator,递归终止
    }
    static int solution_teminator(int n)
    {
        return 0;
    }
};
/*
这里把函数类型设置为static的原因
参考:
问题的原因其实就是函数参数不匹配的问题。因为我们普通的成员函数都有一个隐含的this指针,表面上看我们的谓词函数com()只有两个参数,但实际上它有三个参数,而我们调用sort()排序函数的时候只需要用到两个参数进行比较,所以就出现了形参与实参不匹配的情况(函数有三个形参,但是只输入了两个实参)。
所以,解决办法就是把谓词函数com()定义为static成员函数
*/
 
 
/*
方法二:使用&&逻辑与的短路特性,前面为假,后面的不计算
利用短路特性终止递归向深处延伸
*/
class Solution
{
public:
    int Sum_Solution(int n)
    {
        int ans = n;
        ans && (ans += Sum_Solution(n - 1)); //前面为0时,终止后面计算,递归结束
        return ans;
    }
};
 
 
 
原文地址:https://www.cnblogs.com/wikiwen/p/10229503.html