47、剑指offer--求1+2+3+...+n
题目描述
求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
解题思路:本题采用递归的方式实现,主要点是递归条件的终止。本题巧妙的采用ans && (ans += Sum_Solution(n - 1));,当ans为0时,直接不执行(ans += Sum_Solution(n - 1))。
1 #include <iostream> 2 using namespace std; 3 class Solution { 4 public: 5 6 int Sum_Solution(int n) { 7 int ans = n; 8 ans && (ans += Sum_Solution(n - 1));//此处控制n = 0,时结束累加 9 return ans; 10 } 11 12 }; 13 int main() 14 { 15 int n; 16 while(cin>>n) 17 { 18 Solution s; 19 cout<<s.Sum_Solution(n)<<endl; 20 } 21 return 0; 22 }
解题思路二:利用构造函数求解,执行n此构造函数来获取结果。
1 class Temp 2 { 3 public: 4 Temp(){++N; Sum+=N;} 5 static void Reset(){N = 0; Sum = 0;} 6 static unsigned int GetSum(){return Sum;} 7 private: 8 static unsigned int N; 9 static unsigned int Sum; 10 }; 11 unsigned int Temp::N = 0; 12 unsigned int Temp::Sum = 0; 13 unsigned int Sum_Solution1(unsigned int n) 14 { 15 Temp::Reset(); 16 Temp *a = new Temp[n]; 17 delete []a; 18 a = NULL; 19 return Temp::GetSum(); 20 }