偶爾看到的一道題,和哥們幾個討論了一下,這玩意,不是循環就是遞歸了麼,固然,只要達到目的,管他什麼循環遞歸,對吧。如今總結一下咱們能想到的全部的方法,你們有新的想法歡迎跟帖討論~~
ios
ok,開工。
c++
第一條,最簡單的,直接輸出。(由於輸出結果都差很少,就不一個一個截圖了)spa
printf("5 4 3 2 1\n");
第二條,簡單的循環。code
// for 循環 for(int =5; i !=0; i--) { printf("%d\n",i); } // while 循環 int i=6; while(--i){ printf("%d\n",i); } // do while 循環 int i=5; do{ prinf("%d\n",i); }while(--i);
三,遞歸。如今基本循環是講完了,來討論一下遞歸吧,先來個簡單點的。遞歸
#include <stdio.h> void print(int i) { if(i){ printf("%d\n",i); print(--i); } } int main() { print(5); return 0; }
而後另外一哥們呵呵一笑,來了個短路遞歸。it
#include <stdio.h> int print(int n) { printf("%d\n",n); --n && print(n); } int main() { print(5); return 0; }
四,c++上場。羣裏有個用c++的哥們不服了,也來了一段類的構造。io
// c++ #include <iostream> class A{ public : static int n; A(){std::cout<<n--<<std::endl;} }; int A::n=5; int main() { new A[5]; return 0; }
版主說大家這羣渣渣,看哥兒給大家耍耍模版。asm
#include <iostream> using namespace std; template <int T> class F: public F<T+1> { public: F(){cout << T << " ";} }; template <> class F<6> { }; int main() { F<1> fu; cout<<endl; return 0; }
五,遞歸重新歸來。看你們這麼熱鬧,我也想寫一個,可是c++又不熟練,忽然想起gcc的一個特性,main也能夠遞歸啊編譯
// gcc 經過,vs不行,clang 報兩個警告 #include <stdio.h> #include <stdlib.h> void main(int i) { printf("%d\n", 6-i); (&main + (&exit - &main)*(i/5))(i+1); }
6、彙編+開掛。而後一個彙編大牛說話了,大家BB什麼,哥兒寫的代碼大家都看不懂,而後洋氣的甩咱們一張截圖。
class
// 這個在gcc下編譯失敗 #include "stdio.h" int main(){ __asm{ push esi mov esi,0x31 buhaha: push esi call putchar push 0x0a call putchar add esp,8 inc esi cmp esi,0x36 jne buhaha pop esi } return 0; }
咱們一致討論說這個算開掛,不能做數,大神不耐煩又補上兩行代碼
這下你們都沒話說了。。。。。
你覺得這就完了,固然沒有,
咱們還沒反應過來,大神又說話了,哥兒不用匯編也能開掛,呵呵。
// gcc 下編譯成功,運行出現段錯誤 #include <stdio.h> typedef void (*hehe)(); int main(){ static char a[]={0x56, 0x57, 0xBF, 0x78, 0x56, 0x34, 0x12, 0xBE, 0x31, 0x00,0x00, 0x00, 0x56, 0xFF, 0xD7, 0x6A, 0x0A, 0xFF, 0xD7, 0x83,0xC4, 0x08, 0x46, 0x83, 0xFE, 0x36, 0x75, 0xF0, 0x5F, 0x5E, 0xC3}; *(unsigned long *)(&a[3])=(unsigned long)putchar; ((hehe)(&a[0]))(); }
你們都不說話了。。。。。。
總結:說了這麼多c/c++的方法,其餘語言確定也有更「變態」的方法,平時遇到一個問題時可能咱們一我的思路有限,可是和大夥交流一下,總能有各類各樣的解決方案,因此,不要吝嗇大家的解題方法,拿出來你們交流一下吧 :)