Supposing the inputs are two integer values. I want to convert the two integer values to binary, perform binary addition, and give the result with the carry ignored (the integer equivalent). How would I go about doing this.
An idea that comes to mind is to convert them to binary strings in some way and use an algorithm for binary addition, and then ignore the carry (delete the carry character from the string, if the carry exists).
Sample Input
One number : 1
Second number : 3
Sample Output
2
Explanation:
The lowest bit in the sum is 1 + 1 = 0
The next bit is 0 + 1 = 1 (the carry from the previous bit is discarded)
The answer is 10 in binary, which is 2.
You are probably looking for the bitwise XOR (exclusive OR) which will provide the following outputs for the given inputs:
^ | 0 | 1
--+---+--
0 | 0 | 1
--+---+--
1 | 1 | 0
It behaves like binary addition ( 1+1 = 10) but ignores the overflow if both operands are 1.
int a = 5; // 101
int b = 6; // 110
a ^ b; // 3 or 011
This is just an XOR of the two integers in binary. In Java you can do
result = v1 ^ v2;
Related
I'm trying to convert a negative long number (e.g. -1065576264718330231L) to binary.
First, I convert negative number to positive one by removing the sign;
Second, I get the binary of the result from first step;
then I get stuck with "add one" to the binary result of the second step,that is :
please! how to implement the third step?
or do you have other better solutions?!
http://geekexplains.blogspot.com/2009/05/binary-rep-of-negative-numbers-in-java.html
Signed integers/longs use the two-complements notation:
Say you have -6:
6 = 000..000 110 binary
111..111 001 one's complement
111..111 010 add 1
-6 = 111..111 010
The advantage is that normal binary addition works (-6+6=0), there is just one 0.
Of you could simply subtract 6 from 0:
000
110
------ -
0
1 borrow 1 (all ones at the top)
0
...111
111...111010 = -6
Note:
If one borrows (subtracts one of) 0000000, one actually uses an overflow:
(1)0000000 which minus 1 delivers
1111111
Goodies:
long n = -1065576264718330231L;
System.out.println(Long.toUnsignedString(n, 2));
System.out.println(Long.toString(n, 2));
Given the long value is -1065576264718330231L.
long v = -1065576264718330231L;
System.out.println(Long.toBinaryString(v));
Or you can code the algorithm yourself
StringBuilder sb = new StringBuilder();
while (v != 0) {
sb.append(v < 0 ? '1'
: '0');
v <<= 1;
}
System.out.println(sb.toString());
If you want to convert a positive number to negative using 2's complement you can do the following:
long pos = 23;
long neg = ~pos + 1;
System.out.println(pos);
System.out.println(neg);
But all Strings, ints, longs, etc. are inherently stored in binary and are displayed in different formats based on context.
The output is 9 and I can't get my head around the whole bitwise XOR concept.
public class XOR {
public static void main( String[] args ) {
int a = 12;
int b = 5;
int c = a ^ b;
System.out.print( c );
}
}
XOR stands for exclusive or
Exclusive or or exclusive disjunction is a logical operation that outputs true only when inputs differ (one is true, the other is false)
in your case, it's a bitwise comparison, so each 0 and 1 at the same position is compared
first step is to translate values from decimal to binary
12 = 00001100
05 = 00000101
Then, you apply XOR
12 = 00001100
05 = 00000101
XOR = 00001001
Finally, you convert from binary to decimal
00001001 = 9
the XOR operator first converts both of your values into their binary equivalents. Binary operations will apply to corresponding bits, and the XOR operator evaluates to true (1) whenever the corresponding bits are not equal. For example, 2^1 = 3 [10 ^ 01] notice the first bits and the second bits are different, so both bits evaluate to 1.
In your example: 12 ^ 5
12 = 1 1 0 0
5 = 0 1 0 1
The first and the 4th bits are of opposite value, so the first and the fourth bits evaluate to 1, while the remaining bits evaluate to 0, so the solution is 1001 = 9
the following code will check to see if you have any duplicate characters in the string, but i don't understand the if clause:
public static boolean isUniqueChars(String str) {
int checker = 0;
for (int i = 0; i < str.length(); ++i) {
int val = str.charAt(i) - 'a';
if ((checker & (1 << val)) > 0)
return false;
checker |= (1 << val);
}
return true;
}
I tried to look up some references, I am new to bit shifting, all i understand is that << shifts the binary number left or right. Can you explain to me how checker |= (1 << val) works ? and that 'if' statement as well.
I was also going through this book Cracking the Code Interview and ended up googling for a clear explanations. Finally I understood the concept.
Here is the approach.
Note :
We will assume, in the below code, that the string is only lower case āaā through āzā. This will allow us to use just a single int.
Java integer is of size 32
Number of lower case alphabets is 26
So we can clearly set 0/1 (true or false) value inside one integer in
decimal notation.
It is similar to bool visited[32] .
bool uses 1 byte. Hence you need 32 bytes for storing bool visited[32].
Bit masking is a space optimization to this.
Lets start :
You are looping through all the characters in the string.
Suppose on i'th iteration you found character 'b' .
You calculate its 0 based index.
int val = str.charAt(i) - 'a';
For 'b' it is 1. ie 98-97 .
Now using left shift operator, we find the value of 2^1 => 2.
(1 << val) // 1<<1 => 10(binary)
Now let us see how bitwise & works
0 & 0 -> 0
0 & 1 -> 0
1 & 0 -> 0
1 & 1 -> 1
So by the below code :
(checker & (1 << val))
We check if the checker[val] == 0 .
Suppose we had already encountered 'b'.
check = 0000 0000 0000 0000 0000 1000 1000 0010 &
'b' = 0000 0000 0000 0000 0000 0000 0000 0010
----------------------------------------------
result= 0000 0000 0000 0000 0000 0000 0000 0010
ie decimal value = 2 which is >0
So you finally we understood this part.
if ((checker & (1 << val)) > 0)
return false;
Now if 'b' was not encountered, then we set the second bit of checker using bitwise OR.
( This part is called as bit masking. )
OR's Truth table
0 | 0 -> 0
0 | 1 -> 1
1 | 0 -> 1
1 | 1 -> 1
So
check = 0000 0000 0000 0000 0000 1000 1000 0000 |
'b' = 0000 0000 0000 0000 0000 0000 0000 0010
----------------------------------------------
result= 0000 0000 0000 0000 0000 1000 1000 0010
So that simplifies this part:
checker |= (1 << val); // checker = checker | (1 << val);
I hope this helped someone !
Seems like I am late to the party, but let me take a stab at the explanation.
First of all the AND i.e & operation:
0 & 0 = 0
1 & 0 = 0
0 & 1 = 0
1 & 1 = 1
So basically, if you are given a bit, and you want to find out if its 1 or 0, you just & it with a 1. If the result is 1 then you had a 1, else you had 0. We will use this property of the & below.
The OR i.e | operation
0 | 0 = 0
1 | 0 = 1
0 | 1 = 1
1 | 1 = 1
So basically, if you are given a bit, and you want to do something to it so that the output is always 1, then you do an | 1 with it.
Now, In Java the type int is 4 bytes i.e. 32 bits. Thus we can use an int itself as a data-structure to store 32 states or booleans in simpler terms, since a bit can either be 0 or 1 i.e false or true. Since we assume that our string is composed of only lower case characters, we have enough space inside our int to store a boolean for each of the 26 chars!
So first we initialize our data-structure that we call checker to 0 which is nothing but 32 zeros: 0000000000000000000000.
So far so good?
Now we go through our string, for each character, first we get an integer representation of the character.
int val = str.charAt(i) - 'a';
We subtract a from it because we want our integer to be 0 based. So if vals:
a = 0 i.e. `0000000000000000000000`
b = 1 i.e. `0000000000000000000001`
c = 2 i.e. `0000000000000000000010`
d = 4 i.e. `0000000000000000000100`
Now as seen above, a is 32 zeros, but rest of the characters have a single 1 and 31 zeros. So when we use these characters, we left shift each of them by 1, i.e. (1 << val), so each of them have a single 1 bit, and 31 zero bits:
a = 1 i.e. `0000000000000000000001`
b = 2 i.e. `0000000000000000000010`
c = 4 i.e. `0000000000000000000100`
d = 8 i.e. `0000000000000000001000`
We are done with the setup. Now we do 2 things:
First assume all characters are different. For every char we encounter, we want our datastructure i.e. checker to have 1 for that char. So we use our OR property descrived above to generate a 1 in our datastructure, and hence we do:
checker = checker | (1 << val);
Thus checker stores 1 for every character we encounter.
Now we come to the part where characters can repeate. So before we do step 1, we want to make sure that the checker already does not have a 1 at the position corresponding to the current character. So we check the value of
checker & (1 << val)
So with help of the AND property described above, if we get a 1 from this operation, then checker already had a 1 at that position, which means we must have encountered this character before. So we immediately return false.
That's it. If all our & checks return 0, we finally return true, meaning there were no character repititions.
1 << val is the same as 2 to the degree of val. So it's a number which has
just one one in its binary representation (the one is at position val+1, if you count from
the right side of the number to the left one).
a |= b means basically this: set in a all binary flags/ones from the
binary representation of b (and keep those in a which were already set).
The other answers explain the coding operator usages but i don't think they touch the logic behind this code.
Basically the code 1 << val is shifting 1 in a binary number to a unique place for each character for example
a-0001
b-0010
c-0100
d-1000
As you can notice for different characters the place of 1 is different
checker = checker | (1 << val)
checker here is Oring (basically storing 1 at the same place as it was in 1<<val)
So checker knows what characters have already ocurred
Let's say after the occurence of a,b,c,d checker would look like this
0000 1111
finally
if ((checker & (1 << val)) > 0)
checks if that character has already been occured before if yes return false.To explain you should know a little about AND(&) operation.
1&1->1
0&0->0
1&0->0
So checker currently have 1 in places whose corresponding characters have already occured the only way the expression inside if statement is true
if a character occurs twice which leads 1&1->1 > 0
This sets the 'val'th bit from the right to 1.
1 << val is a 1 shifted left val times. The rest of the value is 0.
The line is equivalent to checker = checker | (1 << val). Or-ing with a 0 bit does nothing, since x | 0 == x. But or-ing with 1 always results in 1. So this turns (only) that bit on.
The if statement is similar, in that it is checking to see if the bit is already on. The mask value 1 << val is all 0s except for a single 1. And-ing with 0 always produces 0, so most bits in the result are 0. x & 1 == x, so this will be non-zero only if that bit at val is not 0.
checker |= (1 << val) is the same as checker = checker | (1 << val).
<< is left bit shift as you said. 1 << val means it's a 1 shifted val digits left.
Example: 1 << 4 is 1000. A left bit shift is the same as multiply by 2. 4 left bit shifts are 4 times 1 multiplied by 2.
1 * 2 = 2 (1)
2 * 2 = 4 (2)
4 * 2 = 8 (3)
8 * 2 = 16 = (4)
| operator is bitwise or. It's like normal or for one bit. If we have more than one bit you do the or operation for every bit.
Example:
110 | 011 = 111
You can use that for setting flags (make a bit 1).
The if condition is similar to that, but has the & operator, which is bitwise and. It is mainly used to mask a binary number.
Example:
110 | 100 = 100
So your code just checks if the bit at place val is 1, then return false, otherwise set the bit at place val to 1.
It means do a binary OR on the values checker and (1 << val) (which is 1, left shifted val times) and save the newly created value in checker.
Left Shift (<<)
Shift all the binary digits left one space. Effectively raise the number to 2 to the power of val or multiply the number by 2 val times.
Bitwise OR (|)
In each binary character of both left and right values, if there is a 1 in the place of either of the two numbers then keep it.
Augmented Assignment (|=)
Do the operation (in this case bitwise OR) and assign the value to the left hand variable. This works with many operators such as:-
a += b, add a to b and save the new value in a.
a *= b, multiply a by b and save the new value in a.
Bitwise shift works as follows:
Example: a=15 (bit representation : 0000 1111)
For operation: a<<2
It will rotate bit representation by 2 positions in left direction.
So a<<2 is 0011 1100 = 0*2^7+0*2^6+1*2^5+1*2^4+1*2^3+1*2^2+0*2^1+0*2^0 = 1*2^5+1*2^4+1*2^3+1*2^2 = 32+18+8+4=60
hence a<<2 = 60
Now:
checker & (1<<val),
will always be greater then 0, if 1 is already present at 1<<val position.
Hence we can return false.
Else we will assign checker value of 1 at 1
I've been working on the algorithm and here's what I noticed that would also work. It makes the algorithm easier to understand when you exercise it by hand:
public static boolean isUniqueChars(String str) {
if (str.length() > 26) { // Only 26 characters
return false;
}
int checker = 0;
for (int i = 0; i < str.length(); i++) {
int val = str.charAt(i) - 'a';
int newValue = Math.pow(2, val) // int newValue = 1 << val
if ((checker & newValue) > 0) return false;
checker += newValue // checker |= newValue
}
return true;
When we get the value of val (0-25), we could either shift 1 to the right by the value of val, or we could use the power of 2s.
Also, for as long as the ((checker & newValue) > 0) is false, the new checker value is generated when we sum up the old checker value and the newValue.
public static boolean isUniqueChars(String str) {
int checker = 0;
for (int i = 0; i < str.length(); ++i) {
int val = str.charAt(i) - 'a';
if ((checker & (1 << val)) > 0)
return false;
checker |= (1 << val);
}
return true;
}
1 << val uses right shift operator. Let us say we have character z. ASCII code of z is 122. a-z is 97- 122 = 25. If we multiply 1*(2)^25 = 33554432. Binary of that is 10000000000000000000000000
if checker has 1 on its 26th bit then this statement if ((checker & (1 << val)) > 0) would be true and isUniqueChar would return false.
otherwise checker would turn it's 26th bit on. |= operator(bitwise or and assignment operator) does checker bitwise OR 10000000000000000000000000. Assigns the result to checker.
public class Operators {
public static void main(String[] args) {
int a = 12;
System.out.println("Bitwise AND:"+(12&12));
System.out.println("Bitwise inclusive OR:"+(12|12));
System.out.println("Bitwise exclusive OR:"+(12^12));
}
}
OUTPUT:
Bitwise AND:12
Bitwise inclusive OR:12
Bitwise exclusive OR:0
I understand first two, but not the third.
XOR tells whether each bit is different.
1 XOR 1 = 0
1 XOR 0 = 1
0 XOR 1 = 1
0 XOR 0 = 0
In other words "either but not both"
0011 XOR 0101 = 0110
BITWISE INCLUSIVE OR (|) means normal or operation ,
BITWISEE ExCLUSIVE OR (^) means xor operation
Third one is an XOR operation (Xclusive-OR)
It says, OR should be exclusively:
where similar will be False(0)
and dissimilar will be True(1).
So 12 in binary would be 1100
So, perform bitwise XOR here:
1 1 0 0
1 1 0 0
---------
0 0 0 0
---------
Every column has same digit, either both are 1's or both are 0's
XOR says, both should be different. Hence all zeros
Exclusive or (XOR) is defined as:
0 ^ 0 = 0
1 ^ 0 = 1
0 ^ 1 = 1
1 ^ 1 = 0
That is, it is 0 when two values are the same, 1 if they are different.
So, given two bit patterns which are exactly equal, each XORed bit will evaluate to 0, as each bit will either have 1 in both positions, or 0 in both positions.
I have this code, it results '2'. I googled and searched books but found no good answer that helped me.
int i = 2;
int j = 3;
int x = i & j;
System.out.println (x);
Can anyone can explain.
Here, '&' is the bitwise and operator. Bits are set in the result only if they are set in both of the operands:
Here's the operation:
2: 00000010
& 3: 00000011
-----------
2: 00000010
Of course here, ints are 32 bits, and I only showed the last 8, but the first 24 are all zeroes for these numbers anyway.
It's a bitwise operator.
2 in binary is '10'. 3 in binary is '11'. The bitwise & operator compares them like so:
10
&11
--
10
For each column where both numbers are 1, it will return 1. In this case, the result is '10', which as an int is equal to 2.
Take these examples:
System.out.println(2 & 3);
System.out.println(3 & 4);
System.out.println(8 & 4);
System.out.println(9 & 5);
System.out.println(11 & 7);
// binary representation of above operations
System.out.println(0b10 & 0b11);
System.out.println(0b11 & 0b100);
System.out.println(0b1000 & 0b100);
System.out.println(0b1001 & 0b101);
System.out.println(0b1011 & 0b111);
They result in the output of:
2
0
0
1
3
2
0
0
1
3
Then go back and look at the binary representations and notice how the resulting answers are the Bitwise AND of the numbers (and not the Logical AND &&)
& is a bitwise operator that works as follows:
0 & 0 = 0
1 & 0 = 0
0 & 1 = 0
1 & 1 = 1
and hence 2 & 3 = 2:
2 ==> 00000000000000000000000000000010
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
3 ==> 00000000000000000000000000000011
---------
2 ==> 00000000000000000000000000000010
& is the bitwise AND
&& is the logical AND.
2 & 3 delivers correctly 2.
Expressed in binary representation:
10
11
--
10