【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 ;
     }
};
 
 
 

猜你喜欢

转载自www.cnblogs.com/wikiwen/p/10229503.html