Today my cousin suddenly asked me a question of C's string:
Problem description
For a 01-string length of 5 bits, each bit can be 0 or 1, a total of 32 possible. The first few of them are:
00000
00001
00010
00011
00100
Please output these 32 kinds of 01 strings in order from small to large. Input format this question is not entered.
Output format
Output 32 rows, in order from small to large, each line is a length of 5 01 strings.
Sample output
00000
00001
00010
00011
Because there is no C environment, the Java implementation is as follows:
intFirst , second, third, fourth, fifth; for(first = 0; first <= 1; first + +)) { for(second = 0; second <= 1; second++) { for(third = 0; third <= 1; third++) { for(fourth = 0; fourth <= 1; fourth++) { for(fifth = 0; fifth <=1; fifth++) {System.out.println ( first+ "+ second +" "+ Third +" "+ Fourth +" "+fifth); } } } } }
And then think about that if the length of the 01 string changes, the loop should be written, and then implemented as follows:
intn = 4; intMaxnum = 0; String Maxstr= ""; for(intk = 0; K < n; k++) {Maxstr+ = "1"; } maxnum= Integer.valueof (Maxstr, 2);//Binary goto Decimal for(inti = 0; I <= maxnum; i++) {BigInteger s=NewBigInteger (i + "");//convert to BigInteger typeString B = s.tostring (2);//convert to 2 binaryString before = ""; if(B.length () <N) { for(intj = 0; J < (N-b.length ()); J + +) {before+ = "0"; }} System.out.println (before+b); }
java 01 string