[算法题]输出从1到1000的数

来自coolshell

有这样一个面试题——请把从1到1000的数打印出来,但你不能使用任何的循环语句或是条件语句。更不能写1000个printf或是cout用C/C++语言

个人比较赞赏的思路是下面两个:

1. 函数指针数组结合n/1000的结果作为数组的index。

 

void yesprint(int i);
void noprint(int i);
 
typedef void(*fnPtr)(int);
fnPtr dispatch[] = { yesprint, noprint };
 
void yesprint(int i) {
    printf("%d\n", i);
    dispatch[i / 1000](i + 1);
}
 
void noprint(int i) { /* do nothing. */ }
 
int main() {
      yesprint(1);
}
 

 

2. 构造函数结合静态变量结合数组。

 

class Printer
{
public:
    Printer() { static unsigned i=1; cout << i++ << endl;; }
 
};
 
int main()
{
    Printer p[1000];
}
 

 

posted @ 2011-01-07 14:08  能巴  阅读(344)  评论(0编辑  收藏  举报