剑指offer 面试题17:打印从1到最大的n位数

此题目中n是用整型数字表示的结果的最大位数,n最大为2147483647,而即使是long long 形式的数字,他也只能最大表示9.2*10^18,也就是最大表示19位数字,利用系统内置的数据类型完全不能满足要求,需要用字符串来表示大数。

/**
 *Copyright @ 2019 Zhang Peng. All Right Reserved.
 *Filename:
 *Author: Zhang Peng
 *Date:
 *Version:
 *Description:
**/

#include<iostream>
#include<string>
using namespace std;

void PrintNum(string str)
{
	bool dis = false;   //控制前面的0不显示
	for (int i = 0; i < str.size(); i++)
	{
		if (str[i] != '0'||dis==true)
		{
			cout << str[i];
			dis = true;
		}
			
	}
	cout << endl;
}

int main()
{
	int n = 3;

	//创建和n长度一致的字符串,并初始化为0
	string result(n, '0');

	int carry = 0; //进位
	int len = result.size();
	while (carry==0)
	{
		for (int i = result.size() - 1; i >= 0; i--)
		{
			int add = result[i] - '0'+1+carry;
			if (i != result.size() - 1)        //非最低位不需要加1
				add--;
			if (add >= 10)
			{
				carry = 1;
				result[i] = add - 10 + '0';
			}
			else
			{
				carry = 0;
				result[i] = add + '0';
				break;
			}
		}
		//显示结果
		PrintNum(result);    
	}

    system("pause");
    return 0;
}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值