剑指offer17--打印从1到最大的n位数——java/C++实现

输入数字n,按顺序打印出从1到最大的n位十进制数。

比如输入3,则打印出1,2,3一直到999(最大的3位数)。

 

思路:

因为n没给,所以必须考虑到大数相乘除

得用字符串来处理。

  1. 个位(最低位在str[0])加加
  2. change函数检测是否需要进位,返回值是为了在最高位需要进位的时候停止
  3. pcout输出
#include <iostream>
#include <vector>

using namespace std;

bool change(string & str)
{
	for(int i=0;i<str.size();i++)
	{
		if(str[i]==('9'+1))
		{
			if(i==str.size()-1)
				return false;
			str[i+1]++;
			str[i]='0';
		}
	}
	return true;
}

void pcout(string & str)
{
	bool flag=false;
	for(int i=str.size()-1;i>=0;i--)
	{
		if(str[i]!='0')
		{
			flag=true;
			cout<<str[i];
		}else{
			if(flag)
				cout<<str[i];
		}
	}
	cout<<endl;
}

void Printout(int n)
{
	if(n<=0)
		return;
	string str(n,'0');
	//while(str[str.size()-1]!='9')
	while(1)
	{
		str[0]++;
		if(!change(str))
			break;
		pcout(str);
	}
}

int main()
{
	int x=3;
	Printout(x);
	return 0;
}

递归地显示全排序:

#include <iostream>

using namespace std;

void pcout(string& str,int n)
{
	bool flag = false;
	for (int i = 0; i <n; i++)
	{
		if (str[i] != '0')
		{
			flag = true;
			cout << str[i];
		}else{
			if (flag)
				cout << str[i];
		}
	}
	cout << endl;
}
void PrintOutRecursively(string& str, int n, int a)
{
	if (a == n-1)
	{
		pcout(str,n);
		return;
	}
	for (int i = 0; i < 10; i++)
	{
		str[a + 1] = i + '0';
		PrintOutRecursively(str, n, a + 1);
	}
}

void Printout(int n)
{
	if (n < 0) return;
	string str(n, '0');
	for (int i = 0; i < 10; i++)
	{
		str[0] = i + '0';//从高向低递归
		PrintOutRecursively(str,n,0);
	}
}


int main()
{
	int x = 3;
	Printout(x);
	return 0;
}

Java解法

class Solution {

    public static int[] printNumbers(int n) {
        if (n <= 0) {
            return new int[0];
        }
        int[] res = new int[(int) Math.pow(10, n) - 1];
        char[] a = new char[n];
        for (int i = 0; i < n; i++) {
            a[i] = '0';
        }
        for (int i = 0; i < (int) Math.pow(10, n) - 1; i++) {
            a[0]++;
            res[i] = calVal(a);
            calA(a);
        }
        return res;
    }

    private static void calA(char[] a) {
        for (int i = 0; i < a.length; i++) {
            if (a[i] == ('9' + 1)) {
                a[i] = '0';
                a[i + 1]++;
            }
        }
    }

    private static int calVal(char[] a) {
        int aVal = 0;
        for (int i = 0; i < a.length; i++) {
            aVal += (a[i] - '0') * (int) Math.pow(10, i);
        }
        return aVal;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值