You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: lessons/bitwise-operator.md
+29-17Lines changed: 29 additions & 17 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -5,10 +5,10 @@ order: "10B"
5
5
section: "Maths for DSA"
6
6
description: "learn maths required in DSA"
7
7
---
8
+
In this lesson, we are going to learn about the bit-wise operators, and some Bit-manipulation techniques to get optimized solutions. These concepts are very important from competitive programming as well as interviews point of view. Okay, so let's learn these techniques:
8
9
9
-
# Bit Manipulation
10
+
##Bit Manipulation
10
11
11
-
## What is Bit Manipulation?
12
12
Bit manipulation is the process of applying logical operations on a sequence of bits, the smallest form of data in a computer, to achieve a required result. Bit manipulation has constant time complexity and process in parallel, meaning it is very efficient on all systems.
13
13
14
14
Most programming languages will have you work with abstractions, like objects or variables, rather than the bits they represent. However, direct bit manipulation is needed to improve performance and reduce error in certain situations.
@@ -30,7 +30,7 @@ Bit manipulation is also a common topic in coding interviews, especially with FA
30
30
If you’re applying for a role that will work with embedded systems or other low-level systems, you’ll encounter more bit questions. In short, the closer your role is to machine level, the more bit manipulation questions you’ll encounter.
31
31
32
32
The best way to prepare for bit manipulation questions is to practice using each bitwise operator and brush up on your binary to decimal conversions.
33
-
# Bitwise Operator In Java
33
+
# Bitwise Operators In Java
34
34
You are no doubt familiar with the arithmetic operators such as + - * / or %. You are also aware of logical operators such as & or |. Turns out there is another, a slightly less known set of operators, which manipulate numbers on bit level. Internally, every number is stored in a binary format - that is 0 and 1. Bitwise operators are used for performing manipulation of bits of a number. These can be used with any type of integer data types (char, short, int, etc).
35
35
36
36
These operators can be performed on integer types -
@@ -40,7 +40,8 @@ These operators can be performed on integer types -
40
40
* int (32 bit)
41
41
* long (64 bit), and even
42
42
* char (16 bit)
43
-
43
+
44
+
Now let's see its type one by one:
44
45
## 1. Unary bitwise complement [~]
45
46
This fancy name basically means bit negation. It takes every single bit of the number and flips its value,i.e, ~0 becomes 1 and vice versa. It is the 1's complement of the number. Unary means that it needs just one operand. The operator is `~` and it is just placed before the number:
46
47
```java
@@ -146,7 +147,7 @@ a= 5
146
147
## 5. Signed Left Shift [<<]
147
148
Signed Left Shift takes two operands. It takes the bit pattern of the first operand and shifts it to the left by the number of places given by the second operand. For example 5 << 3: What happens in this case - Every bit in the binary representation of the integer 5 is shifted by 3 positions to the left. All the places on the left are padded by zeros. That is: `00000101` becomes `00101000`.
148
149
149
-
You can note that the integer result of 5 << 3 is 40. That shows that shifting a number by one is equivalent to multiplying it by 2, or more generally left shifting a number by n positions is equivalent to multiplication by `2^n`.
150
+
You can note that the integer result of 5 << 3 is 40. That shows that shifting a number by one is equivalent to multiplying it by 2, or more generally left shifting a number by n positions is equivalent to multiplication by `2^n`. In this case, it is 5*2^3 = 40.
150
151
151
152
* Even though you can use shifting of byte, short or char, they are promoted to 32-bit integer before the shifting
152
153
* Bit-shift operators never throw an exception
@@ -178,22 +179,33 @@ Unlike the signed shift, the unsigned one does not take sign bits into considera
178
179
a =10
179
180
a>>>1=5
180
181
181
-
Example2:
182
182
a =-10
183
183
a>>>1=2147483643
184
184
DOESNOT preserve the sign bit.
185
185
```
186
+
This operator shifts the first operand to the specified number of bits to the right. Excess bits shifted off to the right are `discarded`. Zero bits are shifted in from the left. The sign bit becomes 0, so the result is `always non-negative`. Unlike the other bitwise operators, zero-fill right shift returns an unsigned 32-bit integer.
187
+
188
+
For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result. For example, 9 >>> 2 yields 2, the same as 9 >> 2:
186
189
## 8. Unsigned Left Shift [<<<]
187
190
Unlike unsigned Right Shift, there is no “<<<” operator in Java, because the logical (<<) and arithmetic left-shift (<<<) operations are identical.
Now, let’s look at a few tricks you can do using bitwise operators.
231
243
232
244
These are often used as interview questions to check if you’ve reviewed basic bit manipulation and can apply it to day-to-day coding tasks.
233
-
## Q1. Check for EVEN / ODD
245
+
###Q1. Check for EVEN / ODD
234
246
To check a number is even or odd, we need to look at the number in its binary form first, lets take an eg, 4 ,i.e, `0100`, if we look carefully then we will find out that the 1 present in the number is at `power of 2` position, lets take another example now, 6 ,i.e, `0110`, here both the 1's are at `power of 2` position and now we can conclude that in binary form if the number is at power of 2 position the it is even. Lets check for odd no. now, eg, 5 ,i.e, `0101` here the least significant digit(or `LSD`) is `not` at the `power of 2` position and thus it is odd.
235
247
236
248
Now, lets look how to solve this,
@@ -242,7 +254,7 @@ if (x & 1 ) == 0
242
254
else
243
255
returnfalse;
244
256
```
245
-
## Q2. Convert characters to uppercase / lowercase
257
+
###Q2. Convert characters to uppercase / lowercase
246
258
This trick tests your knowledge of uppercase and lowercase characters in binary. You can convert any character, `ch`, to the opposite case using `ch ^= 32`.
247
259
248
260
This is because the binary representation of lowercase and uppercase letters are nearly identical, with only 1 bit of difference.
@@ -285,7 +297,7 @@ public class Test
285
297
Toggle case: cHErRy
286
298
Original string: CheRrY
287
299
```
288
-
## Q3. Find Number of Setbits
300
+
###Q3. Find Number of Setbits
289
301
```java
290
302
classCountSetBit {
291
303
privatestaticinthelper(intn) {
@@ -312,7 +324,7 @@ In this approach, we count only the set bits. So,
312
324
313
325
* If a number has 2 set bits, then the while loop runs two times.
314
326
* If a number has 4 set bits, then the while loop runs four times.
315
-
## Q4. Single Number
327
+
###Q4. Single Number
316
328
You are given an array in which every number appears twice except one number, return that number.
317
329
```java
318
330
classSingleNumber {
@@ -341,7 +353,7 @@ This solution relies on the following logic:
341
353
* For n numbers, the below math can be applied: a ^ b ^ a = (a ^ a) ^ b = 0 ^ b = b
342
354
343
355
Therefore, we can XOR all bits together to find the unique number.
0 commit comments