0%

8. Bitwise Operation

Bitwise Operation

num[index] * 2^(index-1)

AND

both
& : return 1 if both has 1 (same)

  1. change num into bitwise
  2. &

    5 & 9
    5 –> 0101(2)
    9 –> 1001(2)
    0101

    &1001

    0001(2) –> 1

OR

at least
| : return 1 if at least one has 1

  1. change num into bitwise
  2. |

    5 | 9
    5 –> 0101(2)
    9 –> 1001(2)
    0101

    1001
    1101(2) –> 13

XOR

just one
^ : return 1 if the value is different, return 0 if same

  1. change num into bitwise
  2. ^

    5 ^ 9
    5 –> 0101(2)
    9 –> 1001(2)
    0101

    ^1001

    1100(2) –> 12

NOT

~ : return the oppostie value

actually, there are 0 as many as the size of the integer range(<=256, thus 8개) in front of the bits

  • -(x) -1 (// in JS)
  • negative
    • starts from -1
    • meaning of 0, 1 is swtiched: 0 -> decrement

      ~5
      5 –> 0101(2)

      ~0101(2)

      1010(2) –> -6 (in JS, normally -5) // 1011(2) –> -5 in JS

Left Shift

<< n : shift bits to the left to the n extent and fill the right bit with 0

5 << 1
0101(2)
—– << 1
1010(2)

Sign-propagating Right Shift

>> n : shift bits to the right to the n extent and fill the left bit with the same one as the original last right value which is sign property

8 >>> 1
0…1000(2)
———– >> 1
00…0100(2) // 4
-8 >>> 1
1…1000(2)
———– >> 1
11…1100(2) // -4

Zero-fill Right Shift

>>> n : shift bits to the right to the n extent and fill the left bit with 0

[1]1…0111 // -8
——— >>> 1
[0]1…1011 // 2147483644

blog.logrocket.com/interesting-use-cases-for-javascript-bitwise-operators/
Interesting use cases for JavaScript bitwise operators - LogRocket Blog
Although we don’t often see bitwise operators used in JavaScript, they have some cool use cases. Learn their theory and implementation.
blog.logrocket.com


compare multiple values together
first comparison -> compare with the next one -> (((repeat)))

Algorithm

qiao.github.io/PathFinding.js/visual/
PathFinding.js
qiao.github.io

Dijkstra

  • only need the weight
  • evaluate all the nodes -> slower
  1. set the weight of starting point to 0, and others to INF (as not started yet)

A*

  • only evaluate shorter distance ->faster
  • need weight and distance both
  1. set additional array with distance