看到這個問題,第一個反應是真變態啊。 然后,直覺是不能用循環就只能用遞歸了。可遞歸怎么跳出來卻遇到了麻煩, 我連goto語句都考慮了也沒弄好。
后來想到一個非常NC的方法:查找表。 如果n限定一個比較小的范圍直接用查找表好了。 但題目的目的肯定不是這樣的.....
后來,我轉換了一下思路 1+2...+n = (n*n + n)>>1 只要求出n*n來就好了, 但問題是不能用乘法,於是硬件出身的我想到了二進制&,|,>>,<<都是可以用的。
思路:設n = 5 則 n = 1 0 1 b. n * n =
1 0 1
* 1 0 1
--------------------
1 0 1 5
0 0 0
1 0 1 20
---------------------
1 1 0 0 1 25
我們只要把中間那一段的數求出來,加起來就好了。 代碼實現中,因為不能寫for,我又懶得自己寫太多遍加法,於是設定n的取值范圍只能是 0-255
/* 題目: 計算 1+2+3+...+n 要求:不可用 乘除 if else for while switch case ?: */ #include <stdio.h> const unsigned char b[16] = {1, 1<<1, 1<<2, 1<<3, 1<<4, 1<<5, 1<<6, 1<<7, 1<<8, 1<<9, 1<<10, 1<<11, 1<<12, 1<<13, 1<<14, 1<<15}; int get_add_factor(unsigned char n, unsigned char onebit) { unsigned char b = onebit + (onebit<<1) + (onebit<<2) + (onebit<<3) + (onebit<<4) + (onebit<<5) + (onebit<<6) + (onebit<<7); return n&b; } int addn(unsigned char n) { unsigned char bits[8] = {n&b[0], (n&b[1])>>1, (n&b[2])>>2 ,(n&b[3])>>3, (n&b[4])>>4, (n&b[5])>>5, (n&b[6])>>6, (n&b[7])>>7}; //把數字的每一位取出來 int tmp[8] = {get_add_factor(n, bits[0]), get_add_factor(n, bits[1])<<1, get_add_factor(n, bits[2])<<2, get_add_factor(n, bits[3])<<3, get_add_factor(n, bits[4])<<4, get_add_factor(n, bits[5])<<5, get_add_factor(n, bits[6])<<6, get_add_factor(n, bits[7])<<7}; int pow = tmp[0] + tmp[1] + tmp[2] + tmp[3] + tmp[4] + tmp[5] + tmp[6] + tmp[7]; int ans = (pow + n) >> 1; return ans; } int main() { //addn 的輸入必須是 0 - 255 int r = addn(255); return 0; }
然后,到網上看看別人的答案,我震驚了。原來有這么多種方法啊。
最讓我嘆服的是下面這個版本: 利用邏輯與&&的特性 成功跳出了循環
#include <stdio.h> #include <stdlib.h> #include <string.h> int add_fun(int n, int &sum) { n && add_fun(n-1, sum); //邏輯與 先計算左邊的值 如果 左邊的值不為真 則不會計算右邊 return (sum+=n); } int main() { int sum=0; int n=100; printf("1+2+3+...+n=%d\n",add_fun(n, sum)); return 0; }
方法三:利用類的靜態變量 在構造函數中對靜態變量做加法 構建多個類對象實現求和
#include <iostream> using namespace std; class Temp { public: Temp() { N++; SUM+=N; } static int GetSum() { return SUM; } static void Reset() { N = 0; SUM = 0; } ~Temp(){}; private: static int N; static int SUM; }; //注意分號 別忘了 //初始化類的靜態成員變量 int Temp::N = 0; int Temp::SUM = 0; int Sum(int n) { Temp::Reset(); Temp * a = new Temp[n]; delete [] a; return Temp::GetSum(); } int main() { int a = Sum(100); return 0; }
方法四 利用函數指針.也是非常的巧妙 定義了一個函數指針的數組 只有i = 0的時候 !!i = 0, 其他情況下 !!i = 1 利用這個規則跳出遞歸
#include <iostream> using namespace std; typedef int (*fun)(int); int solution_f1(int i) { return 0; } int solution_f2(int i) { fun f[2]={solution_f1, solution_f2}; return i+f[!!i](i-1); } int main() { cout<<solution_f2(100)<<endl; return 0; }
還有個方法五 利用虛函數的 具體思想其實跟 函數指針很像 這個沒仔細看 因為我虛函數學得不好....
#include <iostream> using namespace std; 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; } }; int solution2_Sum(int n) { A a; B b; Array[0]=&a; Array[1]=&b; int value=Array[1]->Sum(n); return value; } int main() { cout<<solution2_Sum(100)<<endl; return 0; }
