“蓝桥杯”练习:01字串

             “蓝桥杯”基础练习:01字串         

                              

问题描述

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

00000

00001

00010

00011

00100

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

输入格式
本试题没有输入。
输出格式
输出32行,按从小到大的顺序每行一个长度为5的01串。
样例输出
00000
00001
00010
00011
<以下部分省略>
 
解法:用整型数组存放大数的想法,想来想去还是数组方便
于是先用每次从第一个元素开始算数处理,然后调整。
对于数组中每个元素的不溢出,用while()来解决。
#include <stdio.h>
int main(void)
{
int a[5]={0};
int temp;
int times;
int i;
printf("00000\n");
for(times=1;times<=31;times++)
{
    i=0;
    a[i]+=1;
    while(a[i]>=2)
    {
        temp=a[i]/2;
        a[i]=a[i]%2;
        i++;
        a[i]=a[i]+temp;
    }
    for(i=4;i>=0;i--)
    {
        printf("%d",a[i]);
    }
    printf("\n");
}
     return 0;
}
/////////////////////下面我总结一下我在CSDN博客看到的解法//////////////////////
方法一:最简单最暴力的方法(这个也可以有)         ----c++版的
#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~32的二进制数的输出。
#include <iostream>                      ---c++
#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;
}
方法三:十进制转化为二进制法     此方法是网友分享的,虽然代码比较少,但是我比较难理解。    
#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;
}
方法四:方法还是比较简单的,使用五个for循环来控制字串的输出。
#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;
}
————————————————
版权声明:本文为CSDN博主「Turbo码先生」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_34037358/article/details/51509923


全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务