C++列印位元為n的所有數

來源:互聯網
上載者:User

標籤:列印位元為n的所有數

第一種方法:數組和遞迴實現#include <iostream>using namespace std;void General(int b[], int n,int k){    if (n <= 0)//k是列印位元,n是遞迴剩餘位元。    {        if (k != 1)        {            while (b[k - 1] == 0)//去掉最高位的0            {                k--;            }            if (k == 1)return;        }        for (int j = k-1; j >=0; j--)        {            cout << b[j] << " ";            if (j == 0)cout << endl;        }        return;    }    for (int i =0; i < 10; i++)//我感覺我還不是很得心應手。    {        b[n-1] = i;        General(b, n - 1,k);//一位一位的遞迴賦值,賦值範圍是0-9    }}void Grial(int n){    if (n <= 0)return;    int *b = new int[n];//在vs2013中不能使用b[n],因為它會認為n是一個未初始化的值。    memset(b,0,n);    for (int i = 1; i <= n; i++)    {        int k = i;        General(b,i,k);    }}int main(){    Grial(3);    return 0;}

第二種方法,字串實現:

#include <iostream>using namespace std;void ADD(char *str,int n,int &x){    int flags = 1;    char *p = str + n - 1;    while (flags != 0)    {        flags = 0;        if ((*(p) + flags - ‘0‘) == 9)        {            flags = 1;            *(p) = ‘0‘;        }        else        {            *(p) = *(p)-‘0‘ + ‘1‘;        }        p--;        if (*str == ‘9‘ && flags == 1 && *p==‘9‘)//如果最高位已經為9了,且次高位也為9,flags=1        {                                       //那麼判斷已經結束,將標誌位設定為1,返回終止。                   x = 1;            return;        }    }}void Printf(char *str)//列印,除去首部的0{    char *p = str;    while (*p == ‘0‘)    {        p++;    }    cout << p << endl;}void Grial(int n){    if (n <= 0)return;    char *str = new char[n];    memset(str,‘0‘,n);    *(str + n) = ‘\0‘;    int flags = 0;//作為結束標誌。    while (1)    {        Printf(str);        ADD(str,n,flags);//加1.        if (flags == 1)            break;    }}int main(){    Grial(2);    return 0;}

C++列印位元為n的所有數

聯繫我們

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