[算法題]輸出從1到1000的數[轉載]
有這樣一個面試題——請把從1到1000的數打印出來,但你不能使用任何的循環語句或是條件語句。更不能寫1000個printf或是cout。用C/C++語言。
個人比較贊賞的思路是下面兩個:
1. 函數指針數組結合n/1000的結果作為數組的index。
1
void yesprint(int i);
2
void noprint(int i);
3
4
typedef void(*fnPtr)(int);
5
fnPtr dispatch[] =
{ yesprint, noprint };
6
7
void yesprint(int i)
{
8
printf("%d\n", i);
9
dispatch[i / 1000](i + 1);
10
}
11
12
void noprint(int i)
{ /**//* do nothing. */ }
13
14
int main()
{
15
yesprint(1);
16
}
17

2

3

4

5



6

7



8

9

10

11

12



13

14



15

16

17

2. 構造函數結合靜態變量結合數組。
1 class Printer
2 {
3 public:
4 Printer() { static unsigned i=1; cout << i++ << endl;; }
5
6 };
7
8 int main()
9 {
10 Printer p[1000];
11 }
12
2 {
3 public:
4 Printer() { static unsigned i=1; cout << i++ << endl;; }
5
6 };
7
8 int main()
9 {
10 Printer p[1000];
11 }
12
posted on 2011-01-17 10:30 呆人 閱讀(363) 評論(0) 編輯 收藏 引用 所屬分類: 算法