void binary(int n) { if(n < 1) printf("%s\n",A); // Assume A is a global variable else { A[n-1] = ‘0‘; binary(n-1); A[n-1] = ‘1‘; binary(n-1); } }
n=4时输出如下:
0000
1000
0100
1100
0010
1010
0110
1110
0001
1001
0101
1101
0011
1011
0111
1111
完整代码:
#include<stdio.h> #include<stdio.h> char A[4]; /* Code obtained from http://www.studyalgorithms.com */ void binary(int n) { if(n < 1) printf("%s\n",A); // Assume A is a global variable else { A[n-1] = ‘0‘; binary(n-1); A[n-1] = ‘1‘; /* Feel free to copy but please acknowledge studyalgorithms.com */ binary(n-1); } } int main(void) { binary(4); return 0; }
时间: 2024-12-29 11:24:50