File tree 2 files changed +52
-0
lines changed
2 files changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ * Setting Bit: https://www.geeksforgeeks.org/set-k-th-bit-given-number/
3
+ *
4
+ * To set any bit we use bitwise OR (|) operator.
5
+ *
6
+ * Bitwise OR (|) compares the bits of the 32
7
+ * bit binary representations of the number and
8
+ * returns a number after comparing each bit.
9
+ *
10
+ * 0 | 0 -> 0
11
+ * 0 | 1 -> 1
12
+ * 1 | 0 -> 1
13
+ * 1 | 1 -> 1
14
+ *
15
+ * In-order to set kth bit of a number (where k is the position where bit is to be changed)
16
+ * we need to shift 1 k times to its left and then perform bitwise OR operation with the
17
+ * number and result of left shift performed just before.
18
+ *
19
+ * References:
20
+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_OR
21
+ */
22
+
23
+ /**
24
+ * @param {number } number
25
+ * @param {number } bitPosition - zero based.
26
+ * @return {number }
27
+ */
28
+
29
+ export const setBit = ( number , bitPosition ) => {
30
+ return number | ( 1 << bitPosition )
31
+ }
Original file line number Diff line number Diff line change
1
+ import { setBit } from '../SetBit'
2
+
3
+ test ( 'should set bit at the given bit Position' , ( ) => {
4
+ const setBitPos = setBit ( 1 , 0 )
5
+ expect ( setBitPos ) . toBe ( 1 )
6
+ } )
7
+
8
+ test ( 'should set bit at the given bit Position' , ( ) => {
9
+ const setBitPos = setBit ( 1 , 0 )
10
+ expect ( setBitPos ) . toBe ( 1 )
11
+ } )
12
+
13
+ test ( 'should set bit at the given bit Position' , ( ) => {
14
+ const setBitPos = setBit ( 10 , 1 )
15
+ expect ( setBitPos ) . toBe ( 10 )
16
+ } )
17
+
18
+ test ( 'should set bit at the given bit Position' , ( ) => {
19
+ const setBitPos = setBit ( 10 , 2 )
20
+ expect ( setBitPos ) . toBe ( 14 )
21
+ } )
You can’t perform that action at this time.
0 commit comments