zoukankan      html  css  js  c++  java
  • 打印1到最大的n位数*

    注意:需考虑大数问题

    方法一:

    void PrintFrom1ToMax(int n)
    {
    	if (n <= 0)
    		return;
    
    	char* arrPrintStr = new char[n+1];
    	memset(arrPrintStr, '0', n);
    	arrPrintStr[n] = '';
    	while (!Increment(arrPrintStr))
    	{
    		PrintNumber(arrPrintStr);
    	}
    	delete []arrPrintStr;
    }
    
    bool Increment(char* arrNumber)
    {
    	bool bIsOverflow = false;
    	int nTakeOver = 0;
    	int nLength = strlen(arrNumber);
    	for (int i = nLength - 1; i >= 0; i--)
    	{
    		int num = arrNumber[i] - '0' + nTakeOver;
    		if (i == nLength - 1)
    			num++;
    
    		if (num >= 10)
    		{
    			if (i == 0)
    				bIsOverflow = true;
    			else
    			{
    				num -= 10;
    				nTakeOver = 1;
    				arrNumber[i] = '0' + num;
    			}
    		}
    		else
    		{
    			arrNumber[i] = '0' + num;
    			break;
    		}
    	}
    	return bIsOverflow;
    }
    
    void PrintNumber(char* arrNumber)
    {
    	bool bStartPrint = false;
    	int nLength = strlen(arrNumber);
    	for (int i = 0; i < nLength; ++i)
    	{
    		if (!bStartPrint && arrNumber[i] != '0')
    			bStartPrint = true;
    		if (bStartPrint)
    			printf("%c", arrNumber[i]);
    	}
    }
    

      

    方法二(递归):

    void PrintFrom1ToMax(int n)
    {
    	if (n <= 0)
    		return;
    	char* arrNumber = new char[n + 1];
    	arrNumber[n] = '';
    
    	for (int i = 0; i < 10; ++i)
    	{
    		arrNumber[0] = i + '0';
    		PrintFrom1ToMaxRecursively(arrNumber, n, 0);
    	}
    	delete []arrNumber;
    }
    void PrintFrom1ToMaxRecursively(char* arrNumber, int length, int index)
    {
    	if (index == length - 1)
    	{
    		PrintNumber(arrNumber);
    		return;
    	}
    	for (int i = 0; i < 10; ++i)
    	{
    		arrNumber[index + 1] = i + '0';
    		PrintFrom1ToMaxRecursively(arrNumber, length, index + 1);
    	}
    }
    

      

      

  • 相关阅读:
    [Java IO]04_系统标准IO
    [Java IO]03_字符流
    [Java IO]02_字节流
    [Java IO]01_File类和RandomAccessFile类
    [Java 安全]加密算法
    [Java 安全]消息摘要与数字签名
    Java正则速成秘籍(三)之见招拆招篇
    Java正则速成秘籍(一)之招式篇
    Java 枚举
    redis 系列13 集合对象
  • 原文地址:https://www.cnblogs.com/yapp/p/14389053.html
Copyright © 2011-2022 走看看