N-digit mantra
Simple, direct, honest, brave, smart, arrogant, and wretched. Who else is there? --- Only me !!!
Introduction
This is my question for Chen liren several times. I saw him have a bit of love and a little heart-warming. I hope my lover will not be jealous. Wow, it's so sour...
Question
Given the number n, please give a method to print out all the digits whose digits are n, and each digit increases from left to right. For example, when n = 3, (123,124,125,..., 789)
Ideas
First, consider entering n and n as numbers. The meaning can only be 1 ~ 9. enter other information based on the interviewer's intention. The first thought of this question is loop nesting. But how many layers are you nested? n layers? Dude, n is an unknown number. You're stupid, hey. I think this question is classified as a mathematical permutation and combination with conditional increments. This question can be done using recursive functions or non-recursive functions. I feel that non-recursion is better, and it won't overflow functions. It's great. That is stack. Stack stores the required results.
Take an example to see how I did it. For example, n = 3
Stack element changes, as shown below (incomplete, only the beginning)
.......................
Note that 9 has reached the maximum value (note that not every bit has a maximum value of 9, please think about), and then add one to the first digit, extend the stack size to n until the stack is empty, and the algorithm ends.
Lab
Code
Test. cpp
#include
using namespace std;bool n_number(int n);void PutOutStack(int *s,int length);// main functionint main(){int i = 1;while(i <= 9){cout<<"n="<
9 ){cout<<"exception of n_nember input "<
0){// top of stack add 1 if( s[length-1] < 9-n+length){s[length-1]++;break;}// stack pop else{s[length-1] = 0 ;length--;}}// stack is emptyif(length == 0)break;// stack pushwhile( length < n ){s[length] = s[length-1]+1;length ++;}PutOutStack(s,length);}return true;}// put out the stackvoid PutOutStack(int *s,int length){if(length != 0){int i = 0;while( i < length ){cout<