【剑指offer】47.求1+2+3+...+n

题目

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


分析

由于题目说要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C),那么最简单的方式就是利用递归进行化求解该问题。

github链接:JZ47-求1+2+3+…+n


C++代码

#include <iostream>
using namespace std;

class Solution {
    
    
	public:
	    int Sum_Solution(int n) {
    
    
	    	bool x = n > 1 && (n += this->Sum_Solution(n-1)); 
	    	return n;
	    }
};

int main()
{
    
    
	int n;
	Solution s;
	while(cin>>n){
    
    
		cout<<s.Sum_Solution(n);
	}
	
	return 0;
 } 

猜你喜欢

转载自blog.csdn.net/qq_30091945/article/details/108118756
今日推荐