由於unsigned int甚至unsigned long類型不必定能表示很大的n位數,它們的表示範圍是必定的,因此可使用字符串來存儲,並打印git
bool Incerment(char*& str,int n)//每次調用這個函數都會對字符串進行數值的加1 { int index = n-1; int tmp = str[index] - '0' + 1; int offset = 0; while (index>0){//若是index==0則表示已經超出了最大n位數的值,返回false tmp += offset; if (tmp < 10){ ++str[index]; return true; } else{ str[index] = (tmp % 10) + '0'; offset = tmp / 10; } --index; tmp = str[index] - '0'; } return false; } void PrintNum(char*& str,int n) { int i = 0; while (str[i] == '0') ++i; while (i < n+1){ cout << str[i]; ++i; } cout << endl; } void Print1ToNdigits(int n) { if (n < 1)return; char* str = new char[n + 1]; memset(str, '0', sizeof(char)*(n + 1)); while (Incerment(str,n+1)){ PrintNum(str,n); } delete[] str; }
使用遞歸的方式代碼以下:ide
void _Print1ToNdigits2(int index,int n,vector<char>& v) { if (index == n ){ bool isBegin0 = true; for (int i = 0; i < v.size(); ++i){ if (isBegin0&&v[i] == '0'){ ; } else{ cout << v[i]; isBegin0 = false; } } cout << endl; return; } for (int i = 0; i <= 9; ++i){ v[index] = i + '0'; _Print1ToNdigits2(++index, n, v); --index; } } void Print1ToNdigits2(int n) { if (n < 1)return; vector<char> v; v.resize(n); int index = 0; _Print1ToNdigits2(index,n,v); }
《完》
函數