01字串|蓝桥杯

Description

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

00000

00001

00010

00011

00100

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

Input

输入描述:

本试题没有输入。

输入样例:

00000

00001

00010

00011

<以下部分省略>

Output

输出描述:

输出32行,按从小到大的顺序每行一个长度为5的01串。

方法一:暴力

#include <iostream>
using namespace std;
int main()
{
    cout<<"00000"<<endl;
    cout<<"00001"<<endl;
    cout<<"00010"<<endl;
    cout<<"00011"<<endl;
    cout<<"00100"<<endl;
    cout<<"00101"<<endl;
    cout<<"00110"<<endl;
    cout<<"00111"<<endl;
    cout<<"01000"<<endl;
    cout<<"01001"<<endl;
    cout<<"01010"<<endl;
    cout<<"01011"<<endl;
    cout<<"01100"<<endl;
    cout<<"01101"<<endl;
    cout<<"01110"<<endl;
    cout<<"01111"<<endl;
    cout<<"10000"<<endl;
    cout<<"10001"<<endl;
    cout<<"10010"<<endl;
    cout<<"10011"<<endl;
    cout<<"10100"<<endl;
    cout<<"10101"<<endl;
    cout<<"10110"<<endl;
    cout<<"10111"<<endl;
    cout<<"11000"<<endl;
    cout<<"11001"<<endl;
    cout<<"11010"<<endl;
    cout<<"11011"<<endl;
    cout<<"11100"<<endl;
    cout<<"11101"<<endl;
    cout<<"11110"<<endl;
    cout<<"11111"<<endl;
    return 0;
}

方法二:五层循环,从个位开始从小到大输出0、1

#include <iostream>
using namespace std;
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)
            cout<<a<<b<<c<<d<<e<<endl;
  return 0;
}

方法三:模拟二进制算法,每位一到2即+1,原位归0

#include <iostream>
#include <string>
using namespace std;
int main()
{
  int i,j;
  string str="00000";
  for(i=0;i<32;++i)
  {
    cout<<str<<endl;
    str[4]+=1;
    for(j=4;j>=0;--j)
    {
      if(str[j]=='2')
      {
        str[j-1]+=1;
        str[j]='0';
      }
    }
  }
  return 0;
}

方法4:十进制转换为二进制,十进制的0-31即是该题的解

#include <iostream>
using namespace std;
int main()
{
    for(int i=0;i<32;i++){
        cout<<i%32/16<<i%16/8<<i%8/4<<i%4/2<<i%2<<endl;
    }
    return 0;
}

方法5:

#include <iostream>
using namespace std;
int main(){
    for(int i=0;i<=31;i++)
    {
        int a[5]={0};
        int num=i;
        int z=0;
        while(num!=0)     //按照二进制的方式逐个改变每个位置上的数字
        {
            a[z]=num%2;
            z++;
            num/=2;
        }
        for(int j=4;j>=0;j--)
        cout<<a[j];
        cout<<endl;
    }
    return 0;
} 

【PS】本文仅用于自己总结学习笔记,代码可能部分借鉴他人,如有侵权即删

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值