C ++ print all numbers whose digits are n
Method 1: array and Recursion # include
Using namespace std; void General (int B [], int n, int k) {if (n <= 0) // k indicates the number of digits to print, and n indicates the number of digits to be recursive. {If (k! = 1) {while (B [k-1] = 0) // remove the top 0 {k --;} if (k = 1) return ;} for (int j = K-1; j> = 0; j --) {cout <B [j] <"; if (j = 0) cout <endl;} return;} for (int I = 0; I <10; I ++) // I feel that I am not very handy. {B [n-1] = I; General (B, n-1, k); // recursive value assignment of one digit, the value range is 0-9 }}void Grial (int n) {if (n <= 0) return; int * B = new int [n]; // B [n] cannot be used in vs2013, because it considers n as an uninitialized value. Memset (B, 0, n); for (int I = 1; I <= n; I ++) {int k = I; General (B, I, k) ;}} int main () {Grial (3); return 0 ;}
Method 2: String implementation:
# Include
Using namespace std; void ADD (char * str, int n, int & x) {int flags = 1; char * p = str + n-1; while (flags! = 0) {flags = 0; if (* (p) + flags-'0') = 9) {flags = 1; * (p) = '0';} else {* (p) = * (p)-'0' + '1';} p --; if (* str = '9' & flags = 1 & * p = '9') // if the maximum bit is 9, and the next high is 9, flags = 1 {// then the judgment is over, set the flag bit to 1, and return termination. X = 1; return ;}} void Printf (char * str) // print, remove the first 0 {char * p = str; while (* p = '0') {p ++;} cout <p <endl;} void Grial (int n) {if (n <= 0) return; char * str = new char [n]; memset (str, '0', n); * (str + n) = '\ 0'; int flags = 0; // serves as the end mark. While (1) {Printf (str); ADD (str, n, flags); // ADD 1. if (flags = 1) break;} int main () {Grial (2); return 0 ;}