求1+2+3+...+n,不能利用乘除法,以及for,while,if,else;
来源:互联网 发布:软件运营方案书 编辑:程序博客网 时间:2024/06/05 09:56
本题源自剑指offer
--------------------------------------------
思路:1 这种题一般用循环和递归来求解,现在不让用for,if 就是禁止使用循环和递归。因此考的是发散思维。
2 利用构造函数求解
class Solution {public: Solution(){ ++N; sum+=N; } static void reset(){ N=0; sum=0; } static int getSum(){ return sum; }private: static int N; static int sum;}; int Solution::N=0;int Solution::sum=0;int Sum_Solution(int n) { Solution::reset(); Solution *a=new Solution[n]; delete[] a; a=NULL; return Solution::getSum(); }
2 利用虚函数,模拟递归求解
class A;A* Array[2];class A{ public: virtual int Sum(int n){ return 0; }}class B : public A{ virtual int Sum(int n){ return Array[!!n]->sum(n-1)+n; }}int Sum_Solution(int n){ A a; B b; Array[0]=&a; Array[1]=&b; int value=Array[1]->Sum(n); return value;}3 利用函数指针
typedef unsigned int (*fun)(unsigned int);unsigned int Solution3_Teminator(unsigned int n){ return 0;}unsigned int Sum_solution(unsigned int n){ static fun f[2]={Solution3_Teminator,Sum_solution}; return n+f[!!n](n-1);}4 短路递归
int Sum_Solution(int n) { int sum=n; sum && (sum+=Sum_Solution(n-1)); return sum; }
阅读全文
0 0
- 求1+2+3+...+n,不能利用乘除法,以及for,while,if,else;
- 求1+2+…+n,要求不能使用乘除法、for、while、if、else...
- 求1+2+…+n,要求不能使用乘除法、for、while、if、else...
- 求1+2+…+n,要求不能使用乘除法、for、while、if、else...
- 求1+2+3+...+n,要求不能使用乘除法,for,while,if,else,switch,case等关键字以及条件判断语句
- 求1+2+3+...+n,要求不能使用乘除法,for,while,if,else,switch,case等关键字以及条件判断语句
- 求1+2+3+...+n,要求不能使用乘除法,for,while,if,else,switch,case等关键字以及条件判断语句
- 求 1+2+3+..n不能使用乘除法、 for 、 while 、 if 、 else 、 switch 、 case 等关键字以及条件判断语句
- 求1+2+3+...+n,要求不能使用乘除法,for,while,if,else,switch,case等关键字以及条件判断语句
- 求1+2+…+n.要求不能使用乘除法、for、while、if、else、switch、case等关键字
- 求1+2+…+n, 要求不能使用乘除法、for、while、if、else、switch、case和条件语句
- 求1+2+…+n(要求不能使用乘除法、for、while、if、else、switch、case等关键字)
- 求1+2+…+n, 要求不能使用乘除法、for、while、if、else、switch、case和条件语句
- 每天学习一算法系列(12) (求1+2+…+n,不能使用乘除法,for、while、if 、else、switch、case 等关键字以及条件判断语句)
- 题目:求1+2+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字以及条件判断语句(A?B:C)。
- 求1+2+…+n,要求不能使用乘除法、for、while、if、else、switch、case 等关键字以及条件判断语句
- 求1+2+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字以及条件判断语句(A?B:C)
- 求1+2+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字以及条件判断语句(A?B:C)
- 归并排序,堆排序,基数排序,希尔排序,快速排序,交换排序,选择排序和插入排序的总结和比较
- THINKPHP 提供数据表联合查询的简单方法
- 心情很愉快
- 04:错误探测
- Android USB转串口编程
- 求1+2+3+...+n,不能利用乘除法,以及for,while,if,else;
- 如何定位JVM的问题
- iOS UIView、UIImageView旋转产生边界锯齿的完美解决方法
- .net Math.Round方法详解
- Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.hide()' on a null object re
- 分布式 微服务 JAVA语言开发
- Spring之AOP奇葩报错:Null return value from advice does not match primitive return type for
- MyBatis入门(一)
- Springmvc 拦截器的基本配置和使用