首页 > 其他 > 详细

剑指offer——打印从1到最大的n位数

时间:2017-03-21 00:17:06      阅读:198      评论:0      收藏:0      [点我收藏+]

因为unsigned int甚至unsigned long类型不一定能表示很大的n位数,它们的表示范围是一定的,所以可以使用字符串来存储,并打印

bool Incerment(char*& str,int n)//每次调用这个函数都会对字符串进行数值的加1
{
    int index = n-1;
    int tmp = str[index] - ‘0‘ + 1;
    int offset = 0;
    while (index>0){//如果index==0则表示已经超出了最大n位数的值,返回false
        tmp += offset;
        if (tmp < 10){
            ++str[index]; return true;
        }
        else{
            str[index] = (tmp % 10) + ‘0‘;
            offset = tmp / 10;
        }
        --index;
        tmp = str[index] - ‘0‘;
    }
    return false;
}
void PrintNum(char*& str,int n)
{
    int i = 0;
    while (str[i] == ‘0‘)
        ++i;
    while (i < n+1){
        cout << str[i];
        ++i;
    }
    cout << endl;
}
void Print1ToNdigits(int n)
{
    if (n < 1)return;
    char* str = new char[n + 1];
    memset(str, ‘0‘, sizeof(char)*(n + 1));
    while (Incerment(str,n+1)){
        PrintNum(str,n);
    }
    delete[] str;
}

《完》

本文出自 “零蛋蛋” 博客,谢绝转载!

剑指offer——打印从1到最大的n位数

原文:http://lingdandan.blog.51cto.com/10697032/1908548

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!