列印從1到最大的n位元

來源:互聯網
上載者:User

標籤:blog   使用   io   for   re   c   

題目:輸入數值n,按順序列印從1到最大的n位元,例如輸入n=3,則從1,2,3,一直列印到999

陷阱:若使用迴圈遍曆 1- 999...9 並依次輸出,當位元n過大時,無論將其存入int或long或long long都會溢出,故使用字串來類比數字加法

#include <stdio.h>#include <stdlib.h>#include <string.h>void print_cur_number(char *s){    char *p = s;    while( *p != ‘\0‘ )    {        if( *p == ‘0‘ ) // 找到第一個非0數位位置            p++;        else            break;    }    printf("%s\n",p);}int increase_one(char *s){    int i;    int len = strlen(s);    int carry = 0; // 進位標誌    int over = 0; // over=1, 表示當前值已經是n位元的最大值了, 再+1將成為n+1位元    for( i=len-1; i>=0; i-- )    {        int sum = s[i]-‘0‘+carry;        if( i == len-1 )            ++sum; // 第一次迴圈, 最低位+1        if( sum>=10 ) // 當前位>=10, 需要往高一位進一        {            if( i==0 ) // 發生最高位的進位,說明當前值(未+1之前)已經是n位元的最大值了                over = 1;            else // 非最高位的進位            {                sum -= 10;                s[i] = ‘0‘+sum;                carry = 1;            }        }        else // 當前值+1之後, 未發生進位, 結束迴圈        {            s[i] = sum +‘0‘;            break;        }    }    return over;}void print_to_max_n_digit(int n){    char *s = malloc(n+1);    memset(s, ‘0‘, n);    s[n] = ‘\0‘;    if( n<=0 )        return ;    while( !increase_one(s) )    {        print_cur_number(s);    }    free(s);}int main(void){    int n;    printf("列印1-最大的n位元,請輸入n: ");    scanf("%d",&n);    print_to_max_n_digit(n);    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.