一道有趣的面试题:
输入n。输出正三角形。
如图:
代码如下:递归
const int MAX_SIZE=10;
char pic_map[(1<<MAX_SIZE)+1][(2<<MAX_SIZE)+1];
//以(x,y)为顶点画长度为2*n的正三角形。
void print_triangle(int n, int x, int y) {
if(n==1) {
pic_map[x][y]='/';pic_map[x][y+1]='\\';
pic_map[x+1][y-1]='/';pic_map[x+1][y]='_';
pic_map[x+1][y+1]='_';pic_map[x+1][y+2]='\\';
} else {
int new_edge_len=(1<<(n-1));
print_triangle(n-1,x,y);
print_triangle(n-1,x+new_edge_len,y-new_edge_len);
print_triangle(n-1,x+new_edge_len,y+new_edge_len);
}
}
void print_pic(int n) {
int x=0;
int y=(1<<n);
memset(pic_map,' ',sizeof(pic_map));
print_triangle(n, x, y-1);
int print_len=y+1;
for(int i=0;i<y;i++) {
for(int j=0;j<print_len;j++) {
cout<<pic_map[i][j];
}
print_len++;
cout<<'\n';
}
}