列印從1到最大的n位元

來源:互聯網
上載者:User

主要考慮大數問題。n一大很容易超過正數能表示的範圍,因此需要用字元數組類比。

先增加1,再列印。如下


#include <stdio.h>#include <stdlib.h>//溢出返回1,否則0int add(char* number){    int overflow = 0,i,current_value;    int nLength = strlen(number),jinwei = 0;     for(i = nLength - 1; i >= 0; i --){        current_value = number[i] - '0' + jinwei;  //每一位加上進位        if(i == nLength - 1)  //最低位還要加上1            current_value ++;         if(current_value >= 10){  //其實是在等於10的時候,需要進位            if(i == 0)                overflow = 1;  //最高位需要進位時說明已經到了最大值            else{                current_value -= 10;  //不是最高位就要進位操作,首先將當前位減去10,然後設定進位標誌待下一次使用                jinwei = 1;                number[i] = '0' + current_value;            }        }        else{  //不需要進位就把current_value賦值給number位就行            number[i] = '0' + current_value;            break;        }    }     return overflow;}//列印出這個數字,並忽略開頭的0void print_a_number(char* number){    int begin = 0,i;     for(i = 0; i < strlen(number); ++ i){        if(!begin && number[i] != '0')            begin = 1;         if(begin)            printf("%c", number[i]);    }     printf("\t");}void print_all(int n){     char *number = (char*)malloc((n+1) * sizeof(char));    if(n <= 0)return;    memset(number, '0', n);    number[n] = '\0';     while(!add(number)){        print_a_number(number);    }     free(number);}void main(){    print_all(2);    getch();}


參考劍指offer

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.