标签:大数处理
【题目】
输入数字n,按顺序打印出从1到最大的n位十进制数。比如输入3,则打印出1,2,3一直到最大的三位数999。
【分析】
思路1:循环打印,但是遇到大数问题,就不好解决了。
思路2:对大数问题,考虑用字符串储存十进制数,就不会考虑溢出的问题,用字符串模拟数字的加法,再把字符串表达的数字打印出来。
思路3:更简洁的办法是利用全排列递归方法,n位所有十进制数其实就是n个从0到9的全排列
【测试代码】
思路2:
#include<stdio.h>
#include<string.h>
#define false 0
#define true 1
int increment(char* number)
{
int isoverflow = false;
int ntakeover = 0;
int nlength = strlen(number);
for(int i =nlength - 1; i>=0; i--)
{
int nsum = number[i] - ‘0‘ + ntakeover;
if(i == nlength -1)
nsum++;
if(nsum >=10)
{
if(i == 0)
isoverflow = true;
else
{
nsum -= 10;
ntakeover = 1;
number[i] = ‘0‘ + nsum;
}
}
else
{
number[i] = ‘0‘ +nsum;
break;
}
}
return isoverflow;
}
void printnumber(char* number)
{
int isbeginning0 = true;
int nlength = strlen(number);
for(int i = 0 ; i< nlength ; ++i)
{
if(isbeginning0 && number[i] != ‘0‘)
isbeginning0 = false;
if(!isbeginning0)
printf("%c",number[i]);
}
printf("\t");
}
void Print_1N_Digits(int n)
{
if(n<=0)
return ;
char *number = new char[n+1];
memset(number, ‘0‘, n);
number[n] = ‘\0‘;
while(!increment(number))
printnumber(number);
delete []number;
}
void main()
{
Print_1N_Digits(0);
printf("\n");
Print_1N_Digits(-1);
printf("\n");
Print_1N_Digits(1);
printf("\n");
}
思路2:
#include<stdio.h>
#include<string.h>
#define false 0
#define true 1
void printnumber(char* number)
{
int isbeginning0 = true;
int nlength = strlen(number);
for(int i = 0 ; i< nlength ; ++i)
{
if(isbeginning0 && number[i] != ‘0‘)
isbeginning0 = false;
if(!isbeginning0)
printf("%c",number[i]);
}
printf("\t");
}
void Print_1N_Digits_recursively(char *number, int length, int index)
{
if(index == length -1)
{
printnumber(number);
return ;
}
for(int i = 0 ;i <10 ; ++i)
{
number[index + 1] = i +‘0‘;
Print_1N_Digits_recursively(number, length, index+1);
}
}
void Print_1N_Digits(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‘;
Print_1N_Digits_recursively(number, n, 0);
}
delete []number;
}
void main()
{
Print_1N_Digits(2);
printf("\n");
}
标签:大数处理
原文地址:http://blog.csdn.net/xinyu913/article/details/46357893