标签:
今天表弟突然问我一道C的字符串的题目:
问题描述
对于长度为5位的一个01串,每一位都可能是0或1,一共有32种可能。它们的前几个是:
00000
00001
00010
00011
00100
请按从小到大的顺序输出这32种01串。 输入格式 本试题没有输入。
输出格式
输出32行,按从小到大的顺序每行一个长度为5的01串。
样例输出
00000
00001
00010
00011
由于没有C环境,于是用java实现如下:
int first, 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); } } } } }
后来想想如果01字符串的长度发生变化,这循环该怎么写,后来转而实现如下:
int n = 4; int maxNum = 0; String maxStr = ""; for (int k = 0; k < n; k++) { maxStr += "1"; } maxNum = Integer.valueOf(maxStr, 2); //二进制转十进制 for (int i = 0; i <= maxNum; i++) { BigInteger s = new BigInteger(i + ""); //转换为BigInteger类型 String b = s.toString(2); //转换为2进制 String before = ""; if (b.length() < n) { for (int j = 0; j < (n - b.length()); j++) { before += "0"; } } System.out.println(before + b); }
标签:
原文地址:http://www.cnblogs.com/likun-java/p/4462371.html