大数问题:打印从1到最大的n位数

//打印从1到最大的n位数:大数问题,用字符串表示数字来避免溢出
bool increment(char* number){
    bool isOverFlow = false;
    int nTakeOver = 0;
    size_t strLength = strlen(number);
    for (size_t i = strLength - 1; i >= 0; --i){
        int nSum = number[i] - '0' + nTakeOver;
        if (i == strLength - 1)
            nSum++;
        if (nSum >= 10){
            if (i == 0){
                isOverFlow = true;
                break;
            }
            nSum -= 10;
            nTakeOver = 1;
            number[i] = nSum + '0';
        }
        else{
            number[i] = nSum + '0';
            break;
        }
    }
    return isOverFlow;
}
void printNumber(char* number){
    size_t strLength = strlen(number);
    int i = 0;
    while (number[i] == '0') {i++;}
    for (; i < strLength; ++i)
        printf("%c", number[i]);
    printf("\t");
}
void print1ToMaxOfNDigits(int n){
    if (n <= 0)
        return;
    char* number = new char[n + 1];
    memset(number, '0', n);
    number[n] = '\0';
    while (!increment(number))
        printNumber(number);
    delete []number;
    return;
}


//方法二:全排列方法,递归实现
void print1ToMaxDigitsRecursively(char* number, int length, int index){
    if (index == length - 1)
        printNumber(number);
    else{
        for (int i = 0; i < 10; ++i){
            number[index + 1] = '0' + i;
            print1ToMaxDigitsRecursively(number, length, index+1);
        }
    }
}
void print1ToMaxOfNDigits2(int n){
    if (n <= 0)
        return;
    char* number = new char[n + 1];
    for (int i = 0; i < 10; ++i){
        number[0] = i + '0';
        print1ToMaxDigitsRecursively(number, n, 0);
    }
    return;
}
posted @ 2017-08-27 23:23  sold_out  阅读(327)  评论(0编辑  收藏  举报