I have a method that prints out binary formar of numbers:
private static void binary(int n){
for(int i = 1; i < Math.pow(2, n); i++)
System.out.println(Integer.toBinaryString(i));
}
}
Output is like for n = 3:
1
10
11
100
101
110
111
Is there a way to print out like this:
001
010
011
100
101
110
111
private static void binary(int n){
String t = ""; int N = 1<<n;
for (int i=0; i<n;i++) t += "0";
for (int i = 1; i < N; i++) {
String s = Integer.toBinaryString(i);
System.out.println(t.substring(s.length())+s);
}
}
I would write it as
private static void binary(int n){
for(long i = 0, max = 1 << n; i < max; i++) {
String s = Long.toBinaryString(i);
while (s.length() < n) s = '0' + s;
System.out.println(s);
}
}
or more efficiently
private static void binary(int n) {
char[] chars = new char[n];
for (long i = 0, max = 1 << n; i < max; i++) {
for (int j = 0; j < n; j++)
chars[j] = (char) (((i >>> (n - j - 1)) & 1) + '0');
System.out.println(chars);
}
}
binary(3);
prints
000
001
010
011
100
101
110
111
Quick/Dirty version:
System.out.println(Integer.toBinaryString(i+(1<<n)).substring(1));
(obvious flaw if n == the number of bits in an integer, or if you have more bits in your integer than you want to print... so limited, but maybe a bit simpler if you know your inputs)
Try:
String.format("%" + n + "s", Integer.toBinaryString(i)).replace(' ', '0')
It may not be the most efficient solution, but it's simple and short enough.
private static void binary(int n){
for(int i = 1; i < Math.pow(2, n); i++)
System.out.println(String.format("%04d", Integer.parseInt(Integer.toBinaryString(i))));
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.