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

使用函数指针

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//使用函数指针 递归加法
typedef (*fun)(int);
int func1(int n) {
return 0;
}
int func2(int n) {
fun f[2] = {func1, func2};
return n + f[(n != 0)](n - 1);
}
void function1() {
cout << func2(10) << endl;
}
//----->fun2 end

使用静态变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//----->fun2 start
//使用静态变量
class test {
static int N;
static int sum;
public :
test() {
sum += ++N;
}
大专栏  递归加法(day1)lass="function">static void reset() {
N = sum = 0;
}
static int getSum() {
return sum;
}
};
int test::N = 0;
int test::sum = 0;
void function2() {
test::reset();
test *p = new test[10];
cout << test::getSum() << endl;
delete[]p;
}
//--->fun2 end

使用虚函数的编译多态性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//----->fun3 start
//使用虚函数的编译多态性
class A {
public:
virtual int sum(int n) { return 0; };
};
class B : public A {
public:
int sum(int n) {
A a;
B b;
A *p[2] = {&a, &b};
return n + p[(n - 1 != 0)]->sum(n - 1);
}
};
void function3() {
B b;
cout << b.sum(10) << endl;
}
//----->fun3 end

源码github

最新文章

  1. table中某一个tr边框样式设置
  2. Windows Azure Virtual Machine (28) 使用Azure实例级别IP,Instance-Level Public IP Address (PIP)
  3. JavaScript实现字符串的contains函数
  4. ✡ leetcode 158. Read N Characters Given Read4 II - Call multiple times 对一个文件多次调用read(157题的延伸题) --------- java
  5. C++ 多重集的使用
  6. CloudStack服务引擎配置(cloud-engine-service模块)
  7. 多重背包之 HDU -1171Big Event in HDU &amp;HDU -2191悼念512汶川大地震遇难同胞——珍惜现在,感恩生活
  8. poj3308 Paratroopers --- 最小点权覆盖-&amp;gt;最小割
  9. ios 中在容器中移除单个控件的两个方法Subview
  10. 推荐系统架构-(附ppt&amp;代码)
  11. vim基本操作
  12. Android简易实战教程--第九话《短信备份~二》
  13. LVS(二)NAT模型配置
  14. C. Neko does Maths(数论 二进制枚举因数)
  15. vue 父组件给子组件传值,子组件给父组件传值
  16. string.GetHashCode获取值不一样
  17. 浅尝Java(一)
  18. kali 2016.2安装及配置
  19. 洛谷 P1736 创意吃鱼法
  20. YII登陆错误 mcrypt_create_iv()

热门文章

  1. MAC上的爬虫软件怎么选?看完这篇就够了
  2. 牛客寒假算法基础集训营1B题
  3. SQL:找到特定日期每个顾客最高购买量:Find the highest purchase amount ordered by the each customer on a particular date, with their ID, order date and highest purchase amount.
  4. log 处理
  5. python学习笔记(27)-unittest单元测试-测试用例
  6. 2020 CCPC Wannafly Winter Camp Day1-F-乘法
  7. 一文带你了解BOM基本知识
  8. k8s中command、args和dockerfile中的entrypoint、cmd之间的关系
  9. 02-信贷路由项目rose框架拆分dubbo
  10. 对TD tree的使用体验及建议