The difficulty of this topic is that n may be large, more than the range of integer representation, so there are generally two ideas, one is to use a string to represent integers, and to implement the + + operator, the other is to use the topic as a permutation combination, using recursion can be implemented, the following gives the use of recursive implementation of code:
void__print (CharDigit_array[],int Index,intN) {if(Index<0)return;if(Index= = N-1) {digit_array[Index] =' 0 ';//starting from 0 for(inti =0; I <Ten; ++i) {digit_array[Index] = i +' 0 '; cout << Digit_array << Endl; }return; }//This is in order to print is not like the appearance of 0012 such cases, //But be sure to show up like 1002. The entire character array starts with the ' (space) initialized if(digit_array[Index] !="') digit_array[Index] =' 0 '; __print (Digit_array,Index+1, n);//Starting from 1, the bit is 0 o'clock, which is responsible for the previous sentence for(inti =1; I <Ten; ++i) {digit_array[Index] = i +' 0 '; __print (Digit_array,Index+1, n); }}voidPRINTN (intN) {Char*digit_array =New Char[n +1]; for(inti =0; I < n; ++i) {Digit_array[i] ="'; } Digit_array[n] =' + ';//Starting from the first bit to recursion__print (Digit_array,0, n); Delete[]digit_array;}
Test code:
#include "stdafx.h"#include <iostream>usingnamespacestd;int _tmain(int argc, _TCHAR* argv[]){ PrintN(4); return0;}
Program run:
Using recursion can print a large number, specific to the size of the system allocated stack space, n is too large, recursive depth is too large, so that the stack overflow will not be answered. And the first idea at the beginning of the article and the system can allocate the size of the space decided, I think the efficiency of this idea is higher than the recursive implementation, because the recursive implementation is actually doing the + + operation, coupled with the cost of recursion, nature is slow.
One question per day 21: Print from 0 to the maximum number with n-bit integers