Print an integer in binary format in Java - java

I have a number and I want to print it in binary. I don't want to do it by writing an algorithm.
Is there any built-in function for that in Java?

Assuming you mean "built-in":
int x = 100;
System.out.println(Integer.toBinaryString(x));
See Integer documentation.
(Long has a similar method, BigInteger has an instance method where you can specify the radix.)

Here no need to depend only on binary or any other format... one flexible built in function is available That prints whichever format you want in your program.. Integer.toString(int, representation)
Integer.toString(100,8) // prints 144 --octal representation
Integer.toString(100,2) // prints 1100100 --binary representation
Integer.toString(100,16) //prints 64 --Hex representation

System.out.println(Integer.toBinaryString(343));

I needed something to print things out nicely and separate the bits every n-bit. In other words display the leading zeros and show something like this:
n = 5463
output = 0000 0000 0000 0000 0001 0101 0101 0111
So here's what I wrote:
/**
* Converts an integer to a 32-bit binary string
* #param number
* The number to convert
* #param groupSize
* The number of bits in a group
* #return
* The 32-bit long bit string
*/
public static String intToString(int number, int groupSize) {
StringBuilder result = new StringBuilder();
for(int i = 31; i >= 0 ; i--) {
int mask = 1 << i;
result.append((number & mask) != 0 ? "1" : "0");
if (i % groupSize == 0)
result.append(" ");
}
result.replace(result.length() - 1, result.length(), "");
return result.toString();
}
Invoke it like this:
public static void main(String[] args) {
System.out.println(intToString(5463, 4));
}

public static void main(String[] args)
{
int i = 13;
short s = 13;
byte b = 13;
System.out.println("i: " + String.format("%32s",
Integer.toBinaryString(i)).replaceAll(" ", "0"));
System.out.println("s: " + String.format("%16s",
Integer.toBinaryString(0xFFFF & s)).replaceAll(" ", "0"));
System.out.println("b: " + String.format("%8s",
Integer.toBinaryString(0xFF & b)).replaceAll(" ", "0"));
}
Output:
i: 00000000000000000000000000001101
s: 0000000000001101
b: 00001101

Old school:
int value = 28;
for(int i = 1, j = 0; i < 256; i = i << 1, j++)
System.out.println(j + " " + ((value & i) > 0 ? 1 : 0));
Output (least significant bit is on 0 position):
0 0
1 0
2 1
3 1
4 1
5 0
6 0
7 0

check out this logic can convert a number to any base
public static void toBase(int number, int base) {
String binary = "";
int temp = number/2+1;
for (int j = 0; j < temp ; j++) {
try {
binary += "" + number % base;
number /= base;
} catch (Exception e) {
}
}
for (int j = binary.length() - 1; j >= 0; j--) {
System.out.print(binary.charAt(j));
}
}
OR
StringBuilder binary = new StringBuilder();
int n=15;
while (n>0) {
if((n&1)==1){
binary.append(1);
}else
binary.append(0);
n>>=1;
}
System.out.println(binary.reverse());

This is the simplest way of printing the internal binary representation of an integer.
For Example: If we take n as 17 then the output will be: 0000 0000 0000 0000 0000 0000 0001 0001
void bitPattern(int n) {
int mask = 1 << 31;
int count = 0;
while(mask != 0) {
if(count%4 == 0)
System.out.print(" ");
if((mask&n) == 0)
System.out.print("0");
else
System.out.print("1");
count++;
mask = mask >>> 1;
}
System.out.println();
}

Simple and pretty easiest solution.
public static String intToBinaryString(int integer, int numberOfBits) {
if (numberOfBits > 0) { // To prevent FormatFlagsConversionMismatchException.
String nBits = String.format("%" + numberOfBits + "s", // Int to bits conversion
Integer.toBinaryString(integer))
.replaceAll(" ","0");
return nBits; // returning the Bits for the given int.
}
return null; // if the numberOfBits is not greater than 0, returning null.
}

Solution using 32 bit display mask,
public static String toBinaryString(int n){
StringBuilder res=new StringBuilder();
//res= Integer.toBinaryString(n); or
int displayMask=1<<31;
for (int i=1;i<=32;i++){
res.append((n & displayMask)==0?'0':'1');
n=n<<1;
if (i%8==0) res.append(' ');
}
return res.toString();
}
System.out.println(BitUtil.toBinaryString(30));
O/P:
00000000 00000000 00000000 00011110

Simply try it. If the scope is only printing the binary values of the given integer value. It can be positive or negative.
public static void printBinaryNumbers(int n) {
char[] arr = Integer.toBinaryString(n).toCharArray();
StringBuilder sb = new StringBuilder();
for (Character c : arr) {
sb.append(c);
}
System.out.println(sb);
}
input
5
Output
101

There are already good answers posted here for this question. But, this is the way I've tried myself (and might be the easiest logic based → modulo/divide/add):
int decimalOrBinary = 345;
StringBuilder builder = new StringBuilder();
do {
builder.append(decimalOrBinary % 2);
decimalOrBinary = decimalOrBinary / 2;
} while (decimalOrBinary > 0);
System.out.println(builder.reverse().toString()); //prints 101011001

Binary representation of given int x with left padded zeros:
org.apache.commons.lang3.StringUtils.leftPad(Integer.toBinaryString(x), 32, '0')

You can use bit mask (1<< k) and do AND operation with number!
1 << k has one bit at k position!
private void printBits(int x) {
for(int i = 31; i >= 0; i--) {
if((x & (1 << i)) != 0){
System.out.print(1);
}else {
System.out.print(0);
}
}
System.out.println();
}

The question is tricky in java (and probably also in other language).
A Integer is a 32-bit signed data type, but Integer.toBinaryString() returns a string representation of the integer argument as an unsigned integer in base 2.
So, Integer.parseInt(Integer.toBinaryString(X),2) can generate an exception (signed vs. unsigned).
The safe way is to use Integer.toString(X,2); this will generate something less elegant:
-11110100110
But it works!!!

I think it's the simplest algorithm so far (for those who don't want to use built-in functions):
public static String convertNumber(int a) {
StringBuilder sb=new StringBuilder();
sb.append(a & 1);
while ((a>>=1) != 0) {
sb.append(a & 1);
}
sb.append("b0");
return sb.reverse().toString();
}
Example:
convertNumber(1) --> "0b1"
convertNumber(5) --> "0b101"
convertNumber(117) --> "0b1110101"
How it works: while-loop moves a-number to the right (replacing the last bit with second-to-last, etc), gets the last bit's value and puts it in StringBuilder, repeats until there are no bits left (that's when a=0).

for(int i = 1; i <= 256; i++)
{
System.out.print(i + " "); //show integer
System.out.println(Integer.toBinaryString(i) + " "); //show binary
System.out.print(Integer.toOctalString(i) + " "); //show octal
System.out.print(Integer.toHexString(i) + " "); //show hex
}

Try this way:
public class Bin {
public static void main(String[] args) {
System.out.println(toBinary(0x94, 8));
}
public static String toBinary(int a, int bits) {
if (--bits > 0)
return toBinary(a>>1, bits)+((a&0x1)==0?"0":"1");
else
return (a&0x1)==0?"0":"1";
}
}
10010100

Enter any decimal number as an input. After that we operations like modulo and division to convert the given input into binary number.
Here is the source code of the Java Program to Convert Integer Values into Binary and the bits number of this binary for his decimal number.
The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int integer ;
String binary = ""; // here we count "" or null
// just String binary = null;
System.out.print("Enter the binary Number: ");
integer = sc.nextInt();
while(integer>0)
{
int x = integer % 2;
binary = x + binary;
integer = integer / 2;
}
System.out.println("Your binary number is : "+binary);
System.out.println("your binary length : " + binary.length());
}
}

Since no answer is accepted, maybe your question was about how to store an integer in an binary-file.
java.io.DataOutputStream might be what you're looking for: https://docs.oracle.com/javase/8/docs/api/java/io/DataOutputStream.html
DataOutputStream os = new DataOutputStream(outputStream);
os.writeInt(42);
os.flush();
os.close();

Integer.toString(value,numbersystem) --- syntax to be used
and pass value
Integer.toString(100,8) // prints 144 --octal
Integer.toString(100,2) // prints 1100100 --binary
Integer.toString(100,16) //prints 64 --Hex

This is my way to format an output of the Integer.toBinaryString method:
public String toBinaryString(int number, int groupSize) {
String binary = Integer.toBinaryString(number);
StringBuilder result = new StringBuilder(binary);
for (int i = 1; i < binary.length(); i++) {
if (i % groupSize == 0) {
result.insert(binary.length() - i, " ");
}
}
return result.toString();
}
The result for the toBinaryString(0xABFABF, 8) is "10101011 11111010 10111111"
and for the toBinaryString(0xABFABF, 4) is "1010 1011 1111 1010 1011 1111"

It works with signed and unsigned values used powerful bit manipulation and generates the first zeroes on the left.
public static String representDigits(int num) {
int checkBit = 1 << (Integer.SIZE * 8 - 2 ); // avoid the first digit
StringBuffer sb = new StringBuffer();
if (num < 0 ) { // checking the first digit
sb.append("1");
} else {
sb.append("0");
}
while(checkBit != 0) {
if ((num & checkBit) == checkBit){
sb.append("1");
} else {
sb.append("0");
}
checkBit >>= 1;
}
return sb.toString();
}

`
long k=272214023L;
String long =
String.format("%64s",Long.toBinaryString(k)).replace(' ','0');
String long1 = String.format("%64s",Long.toBinaryString(k)).replace(' ','0').replaceAll("(\d{8})","$1 ");
`
print :
0000000000000000000000000000000000000000000
00000000 00000000 00000000 00000000 0000000

Related

Invert a value of bit in digit

I want to invert a value of bit in digit.
The method should invert value by number of bit, like this:
public static void main(String[] args) {
int res = flipBit(7,1);
}
public static int flipBit(int value, int bitIndex) {
String bin = Integer.toBinaryString(value);
char newChar = (char) (bin.charAt(bitIndex) ^ bin.charAt(bitIndex));
//pseudo code
bin[bitIndex] = newChar;
return Integer.parseInt(bin);
}
Mixing mix bitwise operations and strings will not improve the performance and reduces the redubility of code.
Assuming that bitIndex is zero-based, it might be done using XOR operator like that (credits to #Iłya Bursov since he has pointed out it earlier in the comments):
public static int flipBit(int value, int bitIndex) {
if (bitIndex < 0 || bitIndex > 31) {
throw new IllegalArgumentException();
}
return value ^ 1 << bitIndex;
}
Online Demo
A quick recap on how XOR works.
1 ^ 1 => 0
0 ^ 1 => 1
1 ^ 0 => 1
0 ^ 0 => 0
That means zeros 0 in the bit-mask 1 << bitIndex, created by shifting the value of 1 by the given index, will have no impact on the result while applying XOR.
Only a single significant bit of the mask would interact with the value: if it would encounter 1, this bit would be turned into 0, or if there would be 0 at the same position it would result into 1.
Example:
value = 7, index = 2
111 - value
^
100 - bit-mask `1 << bitIndex`
011 - result is `3`
value = 0, index = 0
000 - value
^
001 - bit-mask `1 << bitIndex`
001 - result is `1`
This solution refers to:
I have string of binary in bin like "111" = 7. I need to change a bit in position bitIndex.
Currently bitIndex is zero-based and counted from the front of the string. (This might not be desired and could be changed with the use of bitIndex = binaryText.length() - 1 - bitIndex;)
public class Main
{
public static void main(String[] args) {
String bin = Integer.toBinaryString(7);
int bitIndex = 2;
System.out.println("Original string: " + bin);
System.out.println("String with flipped bit: " + flipBit(bin, 2));
try {
System.out.println("Flipping using number: " + flipBitViaNumber(bin, 2));
} catch (NumberFormatException ex) {
System.err.println("Oops! Not a number: " + bin);
}
System.out.println("Flipping via char array: " + flipBitViaCharArray(bin, 2));
}
public static String flipBit(String binaryText, int bitIndex) {
StringBuilder sb = new StringBuilder(binaryText.length());
for (int i = 0; i < binaryText.length(); i++) {
if (i == bitIndex) {
sb.append(binaryText.charAt(i) == '1' ? '0' : '1');
} else {
sb.append(binaryText.charAt(i));
}
}
return sb.toString();
}
public static String flipBitViaNumber(String binaryText, int bitIndex)
throws NumberFormatException {
int value = Integer.parseInt(binaryText, 2);
int pattern = 1 << (binaryText.length() - 1 - bitIndex);
value = value ^ pattern;
return Integer.toBinaryString(value);
}
public static String flipBitViaCharArray(String binaryText, int bitIndex)
throws NumberFormatException {
char[] chars = binaryText.toCharArray();
chars[bitIndex] = chars[bitIndex] == '1' ? '0' : '1';
return new String(chars);
}
}
Original string: 111
String with flipped bit: 110
Flipping using number: 110
Flipping via char array: 110
Additional information
A Java int consists of 32 bits, see https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html. Java uses the *two's complement as binary representation. Bitwise operations on ints are handled on the Java stack with particular bytecodes which are very fast as neither objects nor method invocations are used.
How about:
String bin = Integer.toBinaryString( value );
char newChar = (char) (bin.charAt(bitIndex) ^ bin.charAt(bitIndex));
StringBuilder sb = new StringBuilder( bin );
sb.setCharAt( bitIndex, newChar );
return sb.toString();

Find the smallest binary number without continous 1

So here is the thing.
I have to write code to show a binary number X's next smallest "code-X number" which is bigger than binary number X.
code-X number is a binary number which have no continuously 1. For example: 1100 is not a code X number because it has 11, and 1001001001 is a code-X number
Here is my code
String a = "11001110101010";
String b = "";
int d = 0;
for(int i = a.length()-1; i>0;i--){
if(a.charAt(i) == '1' && a.charAt(i-1)=='1'){
while(a.charAt(i)=='1'){
b = b + '0';
if(i!=0){i--;}
d++;
}
}
b = b + a.charAt(i);
}
StringBuffer c = new StringBuffer(b);
System.out.println(c.reverse());
I plan on copy the binary string to string b, replace every '1' which next i is '1' into '0' and insert an '1'
like:
1100 ---> 10000
but i have no idea how to do it :)
May you help me some how? Thanks
Try this. This handles arbitrary length bit strings. The algorithm is as follows.
Needed to conditionally modify last two bits to force a change if the number is not a codeEx number. This ensures it will be higher. Thanks to John Mitchell for this observation.
Starting from the left, find the first group of 1's. e.g 0110
If not at the beginning replace it with 100 to get 1000
Otherwise, insert 1 at the beginning.
In all cases, replace everything to the right of the grouping with 0's.
String x = "10000101000000000001000001000000001111000000000000110000000000011011";
System.out.println(x.length());
String result = codeX(x);
System.out.println(x);
System.out.println(result);
public static String codeX(String bitStr) {
StringBuilder sb = new StringBuilder(bitStr);
int i = 0;
int len = sb.length();
// Make adjust to ensure new number is larger than
// original. If the word ends in 00 or 10, then adding one will
// increase the value in all cases. If it ends in 01
// then replacing with 10 will do the same. Once done
// the algorithm takes over to find the next CodeX number.
if (s.equals("01")) {
sb.replace(len - 2, len, "10");
} else {
sb.replace(len- 1, len, "1");
}
while ((i = sb.indexOf("11")) >= 0) {
sb.replace(i, len, "0".repeat(len - i));
if (i != 0) {
sb.replace(i - 1, i + 2, "100");
} else {
sb.insert(i, "1");
}
}
String str = sb.toString();
i = str.indexOf("1");
return i >= 0 ? str.substring(i) : str;
}
Prints
10000101000000000001000001000000001111000000000000110000000000011011
10000101000000000001000001000000010000000000000000000000000000000000
Using raw binary you can use the following.
public static void main(String[] args) {
long l = 0b1000010100000000010000010000000011110000000000110000000000011011L;
System.out.println(
Long.toBinaryString(nextX(l)));
}
public static long nextX(long l) {
long l2 = l >>> 1;
long next = Long.highestOneBit(l & l2);
long cutoff = next << 1;
long mask = ~(cutoff - 1);
return (l & mask) | cutoff;
}
prints
1000010100000000010000010000000010000000000000000000000000000000
EDIT: Based on #WJS correct way to find the smallest value just larger.
This is a slight expansion WJS' 99% correct answer.
There is just one thing missing, the number is not incremented if there are no consecutive 1's in the original X string.
This modification to the main method handles that.
Edit; Added an else {}. Starting from the end of the string, all digits should be inverted until a 0 is found. Then we change it to a 1 and break before passing the resulting string to WJS' codeX function.
(codeX version does not include sb.replace(len-2,len,"11");)
public static void main(String[] args) {
String x = "10100";
StringBuilder sb = new StringBuilder(x);
if (!x.contains("11")) {
for (int i = sb.length()-1; i >= 0; i--) {
if (sb.charAt(i) == '0') {
sb.setCharAt(i, '1');
break;
} else {
sb.setCharAt(i, '0');
}
}
}
String result = codeX(sb.toString());
System.out.println(x);
System.out.println(result);
}

Output of converting binary to Decimal not expected?

Given a binary number as input convert it into base 10 (decimal system). Note that to convert a number 100111 from binary to decimal, the value is 1*2^5 + 0*2^4 + 0*2^3 + 1*2^2 + 1*2^1+ 1*2^0. Also note that 5 here is the length of the binary number.
MyApproach
To convert to decimal,I first converted the code from String to decimal.Then I solved the number till it is greater than 0 and solved the expression.
For example for number 10=0*2^0+1*2^1 and solved the expression in the code.
I am getting a wrong Ans on the last test case.
Can anyone guide me what is wrong in my code.?
Below is my code:
public int convert(String binary)
{
int p=0;
int decimal=0;
int number=Integer.parseInt(binary);
while(number>0)
{
int temp = number%10;
decimal += temp*Math.pow(2, p);
number = number/10;
p++;
//write your code here
}
return decimal;
}
}
Parameters ActualOutput ExpectedOutput
'10011010010' null 1234
Max value of integer is (2^31-1) and the value that you are parsing to int from string in greater than that. Hence try to use Long in place of int ..
below code is working fine.. please check it below..
public static int convert(String binary)
{
int p=0;
int decimal=0;
long number=Long.parseLong(binary);
while(number>0)
{
long temp = number%10;
decimal += temp*Math.pow(2, p);
number = number/10;
p++;
//write your code here
}
return decimal;
}
Simpler, without pow :
int s=binary.length();
for (int pos=0;pos<s;pos++)
{
char c=binary.charAt(pos);
if (c=='1') decimal+=1;
if (pos<s-1) decimal*=2;
}
Why convert it to decimal first? This is quite easy:
public static void main( String[] args ) {
String str = "10011010010";
int len = str.length();
long mult = 1;
long val = 0;
for (int i = len - 1; i >= 0; i--) {
if ( str.charAt( i ) == '1' ) {
val += mult;
}
mult *= 2;
}
System.out.println( val );
}
Your input is above the limit of int in Java, which is 2,147,483,647.
Even if if you change it to long, you won't be able to convert values above 1000000000000000000 (which is equal to 262144 in decimal). Best solution is to calculate by taking character by character without converting the whole string.
So, try the following code,
public static long convert(String binary) {
long pow = 1, decimal = 0;
for (int i = (binary.length() - 1); i >= 0; i--) {
if (binary.charAt(i) == '1') {
decimal += pow;
}
pow *= 2;
}
return decimal;
}

Algorithm to convert a String of decimal digits to BCD

I am looking a way to convert a string to BCD equivalent. I use Java, but it is not a question of the language indeed. I am trying to understand step by step how to convert a string to BCD.
For example, suppose I have the following string;
"0200" (This string has four ASCII characters, if we were in java this string had been contained in a byte[4] where byte[0] = 48, byte[1] = 50, byte[2] = 48 and byte[3] = 48)
In BCD (according this page: http://es.wikipedia.org/wiki/Decimal_codificado_en_binario):
0 = 0000
2 = 0010
0 = 0000
0 = 0000
Ok, I think the conversion is correct but I have to save this in a byte[2]. What Should I have to do? After, I have to read the BCD and convert it to the original string "0200" but first I have to resolve String to BCD.
Find a utility class to do this for you. Surely someone out there has written a BCD conversion utility for Java.
Here you go. I Googled "BCD Java" and got this as the first result. Copying code here for future reference.
public class BCD {
/*
* long number to bcd byte array e.g. 123 --> (0000) 0001 0010 0011
* e.g. 12 ---> 0001 0010
*/
public static byte[] DecToBCDArray(long num) {
int digits = 0;
long temp = num;
while (temp != 0) {
digits++;
temp /= 10;
}
int byteLen = digits % 2 == 0 ? digits / 2 : (digits + 1) / 2;
boolean isOdd = digits % 2 != 0;
byte bcd[] = new byte[byteLen];
for (int i = 0; i < digits; i++) {
byte tmp = (byte) (num % 10);
if (i == digits - 1 && isOdd)
bcd[i / 2] = tmp;
else if (i % 2 == 0)
bcd[i / 2] = tmp;
else {
byte foo = (byte) (tmp << 4);
bcd[i / 2] |= foo;
}
num /= 10;
}
for (int i = 0; i < byteLen / 2; i++) {
byte tmp = bcd[i];
bcd[i] = bcd[byteLen - i - 1];
bcd[byteLen - i - 1] = tmp;
}
return bcd;
}
public static String BCDtoString(byte bcd) {
StringBuffer sb = new StringBuffer();
byte high = (byte) (bcd & 0xf0);
high >>>= (byte) 4;
high = (byte) (high & 0x0f);
byte low = (byte) (bcd & 0x0f);
sb.append(high);
sb.append(low);
return sb.toString();
}
public static String BCDtoString(byte[] bcd) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < bcd.length; i++) {
sb.append(BCDtoString(bcd[i]));
}
return sb.toString();
}
}
There's also this question: Java code or lib to decode a binary-coded decimal (BCD) from a String.
The first step would be to parse the string into an int so that you have the numeric value of it. Then, get the individual digits using division and modulus, and pack each pair of digits into a byte using shift and add (or shift and or).
Alternatively, you could parse each character of the string into an int individually, and avoid using division and modulus to get the numbers, but I would prefer to parse the entire string up front so that you discover right away if the string is invalid. (If you get a NumberFormatException, or if the value is less than 0 or greater than 9999 then it is invalid.)
Finally, once you have assembled the two individual bytes, you can put them into the byte[2].
You can use following:
//Convert BCD String to byte array
public static byte[] String2Bcd(java.lang.String bcdString) {
byte[] binBcd = new byte[bcdString.length() / 2];
for (int i = 0; i < binBcd.length; i++) {
String sByte = bcdString.substring(i*2, i*2+2);
binBcd[i] = Byte.parseByte(sByte, 16);
}
return binBcd;
}
You can try the following code:
public static byte[] hex2Bytes(String str) {
byte[] b = new byte[str.length() / 2];
int j = 0;
for (int i = 0; i < b.length; i++) {
char c0 = str.charAt(j++);
char c1 = str.charAt(j++);
b[i] = ((byte) (parse(c0) << 4 | parse(c1)));
}
return b;
}

How do I format a number left-padded without using String.format in Java 6?

For example, I need to grab an unknown number, let's say 3, and find the binary (2^3) - 1 times, from 0 to 111 (0-7). Obviously, the number of digits I need depends on whatever number 'n' in 2^n.
So, if the number is 3, I would need the output to be:
000
001
010
011
100
101
111
Now obviously I can do this manually with a String.format("%03d", NumberInBinary) operation, but that's hardcoding it for 3 digits. I need to do the equivalent code with an unknown number of digits, how can I do that? (as in String.format("%0nd", yournumber) where n is the number of digits.)
if n = 4, NumberInBinary = 101;
String.format("%0"+n+"d", NumberInBinary);
with output
0101
Why not make use of the already built-in Integer.toBinaryString() and just manually add the zeros using a StringBuilder ?
public static void main(String[] args) {
int max = 5;
for (int i = 0; i < Integer.MAX_VALUE; i++) {
String binary = Integer.toBinaryString(i);
if (binary.length() > max) {
break;
}
System.out.println( prefixWithZeros(binary, max) );
}
}
static String prefixWithZeros(String binary, int n) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n - binary.length(); i++) {
sb.append('0');
}
return sb.append(binary).toString();
}
You could use recursion:
public static void enumerate(String prefix, int remaining) {
if (remaining == 0) {
System.out.println(prefix);
} else {
enumerate(prefix + "0", remaining - 1);
enumerate(prefix + "1", remaining - 1);
}
}
and then call enumerate("", numberOfDigits);
faster, using StringBuffer:
public static void enumerate(StringBuffer prefix, int remaining) {
if (remaining == 0) {
System.out.println(prefix.toString());
} else {
enumerate(prefix.append('0'), remaining - 1);
prefix.deleteCharAt(prefix.length() - 1);
enumerate(prefix.append('1'), remaining - 1);
prefix.deleteCharAt(prefix.length() - 1);
}
}
and then call enumerate(new StringBuffer(), numberOfDigits);

Categories