【剑指offer-解题系列(48)】求1+2+3+...+n
2017-06-08 16:10
211 查看
题目描述
求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。分析
此题目目的是为了考采用取巧的方法,总共可以使用三种方法: 虚函数,
代码实现
class MyClass{
public:
MyClass(){
sum += n;
n++;
}
static void init(){
sum = 0;
n = 1;
}
static int getNum(){
return sum;
}
private:
static int sum;
static int n;
};
int MyClass::sum = 0;
int MyClass::n = 1;
class Base{
public:
Base(){
}
virtual int add(){
}
private:
};
class Derive:Base{
public:
Derive(){
}
virtual int
private:
};
//////////////////////////////////
class Solution {
public:
///////////////构造函数版本
int Sum_Solution1(int n) {
MyClass::init();
MyClass*h = new MyClass
;
int res = h[0].getNum();
return res;
}
///////////////中断条件版本
int Sum_Solution2(int n) {
int res = n;
res && (res+=Sum_Solution(n-1));
return res;
}
///////////////虚函数版本
int Sum_Solution3(int n) {
int res = n;
res && (res+=Sum_Solution(n-1));
return res;
}
};
相关文章推荐
- 【剑指offer-解题系列(30)】最小的K个数
- 【剑指offer-解题系列(35)】第一个只出现一次的字符
- 【剑指offer-解题系列(42)】和为S的连续正数序列
- 【剑指offer-解题系列(47)】孩子们的游戏(圆圈中最后剩下的数)
- 【剑指offer-解题系列(52)】构建乘积数组
- 【剑指offer-解题系列(64)】数据流中的中位数
- 【剑指offer-解题系列(16)】合并两个排序的列表
- 【剑指offer-解题系列(36)】 数组中的逆序对
- 【剑指offer-解题系列(59)】对称的二叉树
- 【剑指offer-解题系列(6)】旋转数组中的最小数
- 【剑指offer-解题系列(53)】正则表达式匹配
- 【剑指offer-解题系列(7、8)】斐波那契数列、跳台阶
- 【剑指offer-解题系列(17)】树的子结构
- 【剑指offer-解题系列(21)】栈的压入、弹出序列
- 【剑指offer-解题系列(31)】 连续子数组的最大和
- 【剑指offer-解题系列(37)】 两个链表的第一个公共结点。
- 【剑指offer-解题系列(53)】表示数值的字符串
- 【剑指offer-解题系列(22)】从上到下打印二叉树
- 【剑指offer-解题系列(60)】按之字形顺序打印二叉树
- 【剑指offer-解题系列(2)】替换空格