Specify number of bits in a String represetation of a binary number - java

I am trying to write a algorithm that will print a powerset of a given set of numbers. I did that with a loop that goes from zero to 2^length of my set. I convert the index i to binary, and whenever there is a one, I print that number. However, since the string does not have any preceding zeros, I am not getting the right output.
For example, if I have a set of three numbers: {2, 3, 4}, when i is 3, I want the string to be "011", but instead it is "11" and I'm getting an output of 2, 3 instead of 3, 4.
Here is my code:
public static void powerset (int[] A){
double powerSetLength = Math.pow(2, A.length);
for (int i=0; i<powerSetLength; i++){
String bin = Integer.toBinaryString(i);
System.out.println ("\nbin: " + bin);
for (int j=0; j<bin.length(); j++){
if (bin.charAt(j)=='1')
System.out.print(A[j] + " ");
}
}
System.out.println();
}
Here is the output that I am getting:
9 7 2
bin: 0
bin: 1
9
bin: 10
9
bin: 11
9 7
bin: 100
9
bin: 101
9 2
bin: 110
9 7
bin: 111
9 7 2
Here is an example of the output that I would like to get:
9 7 2
bin 001
2
I would like to know if there is a way to convert an integer to binary with a specified number of bits so that I can get this output.

One easy way to deal with this problem is assuming that if a digit is missing in the representation, then its value is zero. You can do it like this:
// The number of digits you want is A.length
for (int j=0; j < A.length ; j++) {
// If j is above length, it's the same as if bin[j] were zero
if (j < b.length() && bin.charAt(j)=='1')
System.out.print(A[j] + " ");
}
}
Of course if you can assume that A.length < 64 (which you should be able to assume if you want your program to finish printing in under a year) you could use long to represent your number, and bit operations to check if a bit is set or not:
int len = A.length;
for (long mask = 0 ; mask != (1L << len) ; mask++) {
for (int i = 0 ; i != len ; i++) {
if ((mask & (1L << i)) != 0) {
System.out.print(A[j] + " ");
}
}
System.out.print();
}

String padded = String.format("%03d", somenumber);
or
System.out.printf("%03d", somenumber);
Would each pad to three digits (the 3 in the format specifier). You could additionally build the specifier programatically based on length you need:
String.format("%0" + n + "d", somenumber)
But this is unnecessary if you just need to know if bit N is set. You could just as easily do this:
if ((value & (1L << n)) != 0) { }
Where value is the number, and n is the ordinal of the bit you want. This logically ands the bit in question with the value - if it's set, the result is non-zero, and the if is true. If it is not set, the result is zero, and the if is false.

Related

Need to find even sums of digits in the array

I need to find even sum of digits from an array in Java.
Array: int [] cars = {3, 4, 6, 5};
Output: 8 10
Process:
3 + 4 == 7 --> not even
3 + 6 == 9 --> not even
3 + 5 == 8 --> even (so print it)
4 + 6 == 10 --> even (so print it)
4 + 5 == 9 --> not even
6 + 5 == 11 --> not even
If this is to check two value combination, you can use something like the below,
int[] arr = {1, 2, 3, 4, 5, 6};
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if ((arr[i] + arr[j]) % 2 == 0) {
System.out.println("" + arr[i] + "+" + arr[j] + "=even");
} else {
System.out.println("" + arr[i] + "+" + arr[j] + "=odd");
}
}
}
and the output will look like this
1+2=odd
1+3=even
1+4=odd
1+5=even
1+6=odd
2+3=odd
2+4=even
2+5=odd
2+6=even
3+4=odd
3+5=even
3+6=odd
4+5=odd
4+6=even
5+6=odd
filter the array into two lists, one for odd numbers and another for even numbers, then loop over each list summing each element with all the others and checking the results, at the end of the loop, remove that element.
the benefit of filtering the array to odd and even numbers is that odd + even is always odd, so, eliminating this case saves you some time.

Creating a BitSet where the LSB bit is added as either 1 or 0

I am trying to create a BitSet of 64 bits where I start by having 56 bits, which is separated into groups of 7. Then I check if there are odd number of 1s in each group. If so, then I want to add a 0 bit, else 1. This results in 64 bits totally
for (int i = 1; i <= 8; i++) {
for (int j = 0; j < i * 7; j++) {
if (i < 3) {
if (i == 2 && j < 6) {
temp.set(j, r.nextBoolean());
} else if (i < 2) {
temp.set(j, r.nextBoolean());
}
}
}
if (temp.cardinality() % 2 != 0) {
temp.set(7, false);
} else {
temp.set(7, true);
}
}
Right now, it only gives me 7 or 8 bits

The code has several issues:
Filling the BitSet
The logic in your loop sets in the first iteration the bits at index 0 - 6 and in the second iteration at index 0 - 13. Thus the first group has 8 bits (at index 0 - 7) but the second group has only 6 bits (at index 8 to 13).
See it for yourself and watch the value of j over the iterations.
Group cardinality
temp.cardinality() % 2 != 0 - BitSet.cardinality
Returns the number of bits set to true in this BitSet
(JavaDoc). Thus your evaluating the number of bits for the whole BitSet in each iteration. But you said you want to check the "number of 1s in each group".
Setting LSB
temp.set(7, false); and temp.set(7, true); - Setting the bit at index 7 (LSB) is only appropriate for the first group. But this code is part of the loop. You need to set the LSB of the current group.
My suggestion
I would recommend to split the task into two steps: Fisrt fill the BitSet, then compute the LSB of each group in the BitSet. The code to compute the LSB could look like:
protected static void computeLsbOf8BitGroups(BitSet temp) {
for (int i = 0; i < temp.size() / 8; i++) {
int msb = i * 8;
BitSet group = temp.get(msb, msb + 8);
temp.set(msb + 7, group.cardinality() % 2 == 0);
}
}

Output of converting string into number does not come as expected

Given a string as input, convert it into the number it represents. You can assume that the string consists of only numeric digits. It will not consist of negative numbers. Do not use Integer.parseInt to solve this problem.
MyApproach
I converted string to char array and stored the original number but I am unable to convert it into a single number
I tried converting individual elements but the digits can be of any length.So,It was difficult to follow that approach.
Hint:I have a hint that the numbers can be added using place values
For e.g if the number is 2300.I stored each number in the form of arrays.Then it should be 2*1000+3*100+0*10+0=2300
But I am unable to convert it into code.
Can anyone guide me how to do that?
Note I cannot use any inbuilt functions.
public int toNumber(String str)
{
char ch1[]=str.toCharArray();
int c[]=new int[ch1.length];
int k=0;
for(int i=0;i<c.length;i++)
{
if(ch1[i]==48)
{
c[k++]=0;
}
else if(ch1[i]==49)
{
c[k++]=1;
}
else if(ch1[i]==50)
{
c[k++]=2;
}
else if(ch1[i]==51)
{
c[k++]=3;
}
else if(ch1[i]==52)
{
c[k++]=4;
}
else if(ch1[i]==53)
{
c[k++]=5;
}
else if(ch1[i]==54)
{
c[k++]=6;
}
else if(ch1[i]==55)
{
c[k++]=7;
}
else if(ch1[i]==56)
{
c[k++]=8;
}
else if(ch1[i]==57)
{
c[k++]=9;
}
}
}
You don't need to do powers or keep track of your multiplier. Just multiply your running total by 10 each time you add in a new digit. And use c - '0' to turn a character into a number:
int n = 0;
for (int i = 0; i < str.length(); i++) {
n = n * 10 + str.charAt(i) - '0';
}
So for example for 1234 it goes
0 * 10 + 1 = 1
1 * 10 + 2 = 12
12 * 10 + 3 = 123
123 * 10 + 4 = 1234
A digit character ('0'-'9') can be converted into an integer value (0-9) using:
ch - '0'
This is because the digit characters are all consecutive in ASCII/Unicode.
As for calculating the full number, for the input 2300, you don't want:
2 * 1000 + 3 * 100 + 0 * 10 + 0
Instead, you'll want a more incremental approach using a loop:
r = 0
r = r * 10 + 2 (2)
r = r * 10 + 3 (23)
r = r * 10 + 0 (230)
r = r * 10 + 0 (2300)
This is much better than trying to calculate 1000 (Math.pow(10,3)), which your formula would require.
This should be enough information for you to code it. If not, create a new question.
If you loop through the char array you have and take the last value, put it through an if statement and add to an to number integer whatever that number is (use 10 if statements). Next go to the second to last value, and do the same thing only this time multiply the resulting numbers by 10 before adding it to the total number. Repeat this using 1 * 10^(value away from end) being multiplied to the number gotten from the if statements.
Well what comes to my mind when seeing this problem is to multiply the numbers you are getting with your current code with the place they have in the charArray:
int desiredNumber = 0;
for(int k=1; k<=c.length; k++) {
desiredNumber += c[k] * (Math.pow(10, c.length - k));
}
If you are not allowed to use the Math.pow() function then simply write one yourself with aid of a loop.
Greetings Raven
You can do
int no = 0;
for(int i = 0; i < c.length; i++){
no += c[i] * Math.pow(10, c.length - 1 - i);
}

Find Kth digit number after n changes

There is a changing rule that, 0 -> 01, 1 -> 10. For example, after the change, 10 is 1001.
Assume that the input is 0, after n changes of such rule, what is the Kth digit?
I can only come with the brutal solution, which is as followings. However I believe there exist better solutions, can anyone come up with some new ideas?
public char lalala(int n, int k) {
String str = "0";
for (int i = 0; i < n; i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < str.length; j++) {
if (str.charAt(j) == '0') {
sb.append("01");
} else {
sb.append("10");
}
}
str = sb.toString();
}
return str.charAt(k);
}
So your generated string will look like
0110100110010110....
Now lets write this numbers vertically and lets print binary representation of position of each digit
value|position -> position binary
-----+---------------------------
0 | 0 -> 0000
1 | 1 -> 0001
1 | 2 -> 0010
0 | 3 -> 0011
1 | 4 -> 0100
0 | 5 -> 0101
0 | 6 -> 0110
1 | 7 -> 0111
. . ....
. . ....
If you take closer look you will see that:
if number of 1 in binary representation of position is even value is 0
if number of 1 in binary representation of position is odd value is 1
which means that
0001, 0010, 0100, 0111 contains odd number of 1 value will be 1.
In other words value is equal of number of ones modulo 2.
Using this fact you can create code which will convert your n to string representing its binary form, sum all ones, and check if it is odd or even.
Code converting n to value can look like this
public static int value(int n) {
String binary = Integer.toBinaryString(n);
return binary.chars().map(e -> e == '1' ? 1 : 0).sum() % 2;
}
(little longer version if you are not familiar with streams introduced in Java 8)
public static int value(Integer n) {
String binary = Integer.toBinaryString(n);
int count = 0;
for (char ch : binary.toCharArray())
if (ch == '1') count ++;
return count % 2;
}
and when you use it like
for (int i = 0; i < 20; i++)
System.out.print(value(i));
you will get as output 01101001100101101001 which seems correct.

(Java) Specify number of bits (length) when converting binary number to string?

I'm trying to store a number as a binary string in an array but I need to specify how many bits to store it as.
For example, if I need to store 0 with two bits I need a string "00". Or 1010 with 6 bits so "001010".
Can anyone help?
EDIT: Thanks guys, as I'm rubbish at maths/programming in general I've gone with the simplest solution which was David's. Something like:
binaryString.append(Integer.toBinaryString(binaryNumber));
for(int n=binaryString.length(); n<numberOfBits; n++) {
binaryString.insert(0, "0");
}
It seems to work fine, so unless it's very inefficient I'll go with it.
Use Integer.toBinaryString() then check the string length and prepend it with as many zeros as you need to make your desired length.
Forget about home-made solutions. Use standard BigInteger instead. You can specify number of bits and then use toString(int radix) method to recover what you need (I assume you need radix=2).
EDIT: I would leave bit control to BigInteger. The object will internally resize its bit buffer to fit the new number dimension. Moreover arithmetic operations can be carried out by means of this object (you do not have to implement binary adders/multipliers etc.). Here is a basic example:
package test;
import java.math.BigInteger;
public class TestBigInteger
{
public static void main(String[] args)
{
String value = "1010";
BigInteger bi = new BigInteger(value,2);
// Arithmetic operations
System.out.println("Output: " + bi.toString(2));
bi = bi.add(bi); // 10 + 10
System.out.println("Output: " + bi.toString(2));
bi = bi.multiply(bi); // 20 * 20
System.out.println("Output: " + bi.toString(2));
/*
* Padded to the next event number of bits
*/
System.out.println("Padded Output: " + pad(bi.toString(2), bi.bitLength() + bi.bitLength() % 2));
}
static String pad(String s, int numDigits)
{
StringBuffer sb = new StringBuffer(s);
int numZeros = numDigits - s.length();
while(numZeros-- > 0) {
sb.insert(0, "0");
}
return sb.toString();
}
}
This is a common homework problem. There's a cool loop that you can write that will compute the smallest power of 2 >= your target number n.
Since it's a power of 2, the base 2 logarithm is the number of bits. But the Java math library only offers natural logarithm.
math.log( n ) / math.log(2.0)
is the number of bits.
Even simpler:
String binAddr = Integer.toBinaryString(Integer.parseInt(hexAddr, 16));
String.format("%032", new BigInteger(binAddr));
The idea here is to parse the string back in as a decimal number temporarily (one that just so happens to consist of all 1's and 0's) and then use String.format().
Note that you basically have to use BigInteger, because binary strings quickly overflow Integer and Long resulting in NumberFormatExceptions if you try to use Integer.fromString() or Long.fromString().
Try this:
String binaryString = String.format("%"+Integer.toString(size)+"s",Integer.toBinaryString(19)).replace(" ","0");
where size can be any number the user wants
Here's a simple solution for int values; it should be obvious how to extend it to e.g. byte, etc.
public static String bitString(int i, int len) {
len = Math.min(32, Math.max(len, 1));
char[] cs = new char[len];
for (int j = len - 1, b = 1; 0 <= j; --j, b <<= 1) {
cs[j] = ((i & b) == 0) ? '0' : '1';
}
return new String(cs);
}
Here is the output from a set of sample test cases:
0 1 0 0
0 -1 0 0
0 40 00000000000000000000000000000000 00000000000000000000000000000000
13 1 1 1
13 2 01 01
13 3 101 101
13 4 1101 1101
13 5 01101 01101
-13 1 1 1
-13 2 11 11
-13 3 011 011
-13 4 0011 0011
-13 5 10011 10011
-13 -1 1 1
-13 40 11111111111111111111111111110011 11111111111111111111111111110011
Of course, you're on your own to make the length parameter adequate to represent the entire value.
import java.util.BitSet;
public class StringifyByte {
public static void main(String[] args) {
byte myByte = (byte) 0x00;
int length = 2;
System.out.println("myByte: 0x" + String.valueOf(myByte));
System.out.println("bitString: " + stringifyByte(myByte, length));
myByte = (byte) 0x0a;
length = 6;
System.out.println("myByte: 0x" + String.valueOf(myByte));
System.out.println("bitString: " + stringifyByte(myByte, length));
}
public static String stringifyByte(byte b, int len) {
StringBuffer bitStr = new StringBuffer(len);
BitSet bits = new BitSet(len);
for (int i = 0; i < len; i++)
{
bits.set (i, (b & 1) == 1);
if (bits.get(i)) bitStr.append("1"); else bitStr.append("0");
b >>= 1;
}
return reverseIt(bitStr.toString());
}
public static String reverseIt(String source) {
int i, len = source.length();
StringBuffer dest = new StringBuffer(len);
for (i = (len - 1); i >= 0; i--)
dest.append(source.charAt(i));
return dest.toString();
}
}
Output:
myByte: 0x0
bitString: 00
myByte: 0x10
bitString: 001010
So here instead of 8 you can write your desired length and it will append zeros accordingly. If the length of your mentioned integer exceeds that of the number mentioned then it will not append any zeros
String.format("%08d",1111);
Output:00001111
String.format("%02d",1111);
output:1111

Categories

Resources