01字串
1.问题详情
问题描述
对于长度为5位的一个01串,每一位都可能是0或1,一共有32种可能。它们的前几个是:
00000
00001
00010
00011
00100
请按从小到大的顺序输出这32种01串。
输入格式
本试题没有输入。
输出格式
输出32行,按从小到大的顺序每行一个长度为5的01串。
样例输出
00000
00001
00010
00011
<以下部分省略>
2.代码
自己写的,感觉步骤有些多
#include<iostream>
using namespace std;
void toBinary(int n){
int m;
string s="";
while(n!=0){
m=n%2;
n=n/2;
if(m==0)
s+="0";
else
s+="1";
}
//长度不够5,补零
if(s.length()==0)
s+="00000";
if(s.length()==1)
s+="0000";
if(s.length()==2)
s+="000";
if(s.length()==3)
s+="00";
if(s.length()==4)
s+="0";
for(int i=s.length()-1;i>=0;i--)//倒序输出
cout<<s[i];
}
int main(){
for(int i=0;i<32;i++){
toBinary(i);
cout<<endl;
}
}
经过搜索后,有更为简洁的做法
#include<iostream>
using namespace std;
int main(){
for(int i=0;i<32;i++){
cout<<i/16%2<<i/8%2<<i/4%2<<i/2%2<<i%2<<endl;//联想十进制与二进制之间的转化
}
}
针对第二种做法,可以联想十进制与二进制之间的转化,如
31
=
2
4
∗
1
+
2
3
∗
1
+
2
2
∗
1
+
2
1
∗
1
+
2
0
∗
1
=
(
11111
)
2
31=2^4*1+2^3*1+2^2*1+2^1*1+2^0*1=(11111)2
31=24∗1+23∗1+22∗1+21∗1+20∗1=(11111)2
就例如i/8%2而言,由中间的表达式可知:
除8以后,小于8的数会消成0(如2^2 ,2^1, 2^0)
等于8的数会消成1(如2^3)
大于8的数会消成2的倍数(如2^4),所以最后再%2就可以得到相应的二进制位,要么是0,要么是1。