"Disclaimer: All rights reserved, please indicate the source of the reprint, do not use for commercial purposes. Contact mailbox: [Email protected] "
Topic Link:http://www.nowcoder.com/practice/7a0da8fc483247ff8800059e12d7caf1?rp=3&ru=/ta/coding-interviews& Qru=/ta/coding-interviews/question-ranking
Title Description
Ask for 1+2+3+...+n, the request cannot use multiplication method, for, while, if, else, switch, case and other keywords and conditional judgment statement (A? B:C).
Ideas
It seems like there is no good way to think about it at first, but if we are familiar with C + + features, or if we know more about recursion, we can find some ways to solve this problem.
1. Using recursion
Class Solution{public:int sum_solution (int n) {int Sum = N;bool flag = (n>0) && ((Sum+=sum_solution (n-1)) >0) ; return sum;}};
2. Constructors
Class temp{public : Temp () { ++n; sum+=n; } static void Reset () { N = Sum = 0; } static int getsum () { return Sum; } Private: static int N; static int Sum;}; int temp::n = 0;int temp::sum = 0; Class solution{public : int sum_solution (int n) { temp::reset (); Temp *a = new Temp[n]; delete []a; A = NULL; return Temp::getsum (); }};
3. Virtual functions
Class A; A * array[2]; Class a{public : virtual int Sum (int n) { return 0; }}, Class B:public a{public : virtual int Sum (int n) { return array[!! N]->sum (n-1) +n; }; Class solution{public : int sum_solution (int n) { a A; b b; Array[0] = &a; ARRAY[1] = &b; return Array[1]->sum (n); }};
Copyright NOTICE: This article is the original blogger article, if reproduced, please indicate the source
"The sword refers to offer" asks 1+2+3+...+n