17打印从1到最大的n位数

每次加一打印,判断长度是否大于n
string addstr(string s)
{
int carry = 1;
for (int i = 0; i < s.length(); i++)
{
carry = carry + s[i] - '0';
s[i] = carry % 10 + '0';
carry /= 10;
}
if (carry)s += carry + '0';
return s;
}
void Print1ToMaxOfNDigits(int n)
{
if (n <= 0)return;
string s = "";
while (s.length() <= n)
{
s = addstr(s);
if (s.length() == n+1)break;//长度为n+1时跳出
for (int i = s.length() - 1; i >= 0;i--)cout << s[i];
cout << " ";
}
}

全排列递归
void show(charnumber)
{
bool isBegin = false;
for (int i = 0; i < strlen(number); i++)
{
if (!isBegin&&number[i] != '0')isBegin = true;
if (isBegin)printf("%c", number[i]);
}
printf("\t");
}
void shownumber(char
number, int length, int index)
{
if (index == length - 1)
{
show(number);
return;
}
for (int i = 0; i < 10; i++)
{
number[index + 1] = i + '0';
shownumber(number, length, index + 1);
}
}
void Print1ToMaxOfNDigits(int n)
{
if (n <= 0)return;
char*number = new char[n + 1];
number[n] = '\0';
for (int i = 0; i < 10; i++)
{
number[0] = i + '0';
shownumber(number, n, 0);
}
delete number;
}

你可能感兴趣的:(17打印从1到最大的n位数)