打印从1到n位最大的数(考虑大数)

考虑大数,已经不能用long long表示了,就要用字符串或数组表示了,下面用字符串表示

#include <iostream>
#include <string>
using namespace std;
//用string表示的十进制数字,加1,超出边界返回false,正常加1返回true
bool plus1(string &str);
//打印string数字,忽略前面的0
void print1(string &str);

int main()
{
    
    
    int n;   //打印1到n为最大的数
    cin >> n;
    string str1(n, '0');

    while (plus1(str1))
    {
    
    
        print1(str1);
    }
    cout << endl;
    return 0;
}

bool plus1(string &str)
{
    
    
    int size = str.size();
    int id = size - 1;
    while (str[id] == '9' && id >= 0)
    {
    
    
        str[id] = '0';
        id--;
    }
    if (id < 0)
        return false; //超界
    str[id] += 1;
    return true;
}

void print1(string &str)
{
    
    
    int size = str.size();
    int i = 0;
    while (str[i] == '0')
    {
    
    
        i++;
    }
    cout << str.substr(i, size - i) << " ";
}

猜你喜欢

转载自blog.csdn.net/qq_41253960/article/details/124501633