码迷,mamicode.com
首页 > 其他好文 > 详细

01字串

时间:2018-07-22 15:13:36      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:格式   遍历   stream   顺序   empty   i++   直接   tac   cout   

问题描述

对于长度为5位的一个01串,每一位都可能是0或1,一共有32种可能。它们的前几个是:
00000
00001
00010
00011
00100

请按从小到大的顺序输出这32种01串。

输出格式

输出32行,按从小到大的顺序每行一个长度为5的01串。
样例输出
00000
00001
00010
00011



解题思路

方法一:

由这些数字可以看出,分别是0-31的二进制表示,所以简单的办法就是直接将0-31用一个for循环转换为二进制输出。

#include <iostream>
#include <stack>

void DecToBin(int num)
{
    int i = 0, mod = 0;
    int N = num;
    std::stack<int> p;

    while (N >= 0 && i < 5)
    {
        if (N != 0)
        {
            mod = N % 2;
            p.push(mod);
            N /= 2;
        }
        else
        {
            //不够5位的用0填充
            p.push(0);
        }
        
        i++;
    }

    while (!p.empty())
    {
        std::cout << p.top();
        p.pop();
    }
    std::cout.put(‘\n‘);
}

int main()
{
    for (int i = 0; i < 32; ++i)
    {
        DecToBin(i);
    }

    return 0;
}

这种转二进制是用的stack方式,还可以这样:

#include <iostream>

int main()
{
    for (int i = 0; i < 32; ++i)
    {
        std::cout << i % 32 / 16
                  << i % 16 / 8
                  << i % 8 / 4
                  << i % 4 / 2
                  << i % 2 << std::endl;
    }

    return 0;
}

因为二进制的权值分别为0, 2, 4, 8, 16, 32, ......,而且前一项的权值一定比后一项大,所以用取余的方式可以等到该位上的数字,然后除去该位的权值,就能等到该位是0还是1。


方法二:

可以直接用5层循环遍历,每一层循环分别控制5位数字的每一位,然后输出即可。

#include <iostream>

int main()
{
    int a, b, c, d, e;
    for (a = 0; a < 2; ++a)
    {
        for (b = 0; b < 2; ++b)
        {
            for (c = 0; c < 2; ++c)
            {
                for (d = 0; d < 2; ++d)
                {
                    for (e = 0; e < 2; ++e)
                    {
                        std::cout << a << b << c << d << e << std::endl;
                    }
                }
            }
        }
    }

    return 0;
}

方法三:

还可以用数组来模拟二进制运算。

#include <iostream>
#include <string>

int main()
{
    int num[5] = { 0 };
    for (int i = 0; i < 32; ++i)
    {   
        std::cout << num[0] << num[1] << num[2] << num[3] << num[4] << std::endl;
        int temp = i;
        int index = 4;
        while (temp >= 1)
        {
            //大于2的向前一位进1,本位归0
            num[index--] = temp % 2;
            temp /= 2;
        }
    }
    return 0;
}

01字串

标签:格式   遍历   stream   顺序   empty   i++   直接   tac   cout   

原文地址:https://www.cnblogs.com/coolcpp/p/01binchar.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!