How should I utilize 'twoToThe[i]'

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

How should I utilize 'twoToThe[i]'

Ju Se Hoon


In the lecture, It is recommended to make an static fixed array twoToThe[i].

But how does it work with bit(i, j)??

Read all the forum posts regarding Math.multiply and still have no clue at all...

It's surprising that people just figured things out on their own. I'm curious about the thought process for this.
Reply | Threaded
Open this post in threaded view
|

Re: How should I utilize 'twoToThe[i]'

cadet1620
Administrator
Ju Se Hoon wrote
In the lecture, It is recommended to make an static fixed array twoToThe[i].

But how does it work with bit(i, j)??

Read all the forum posts regarding Math.multiply and still have no clue at all...

It's surprising that people just figured things out on their own. I'm curious about the thought process for this.
Declare "static Array twoToThe;" in class Math.

In Math.init(), create the array and initialize it with 2^0, 2^1, 2^2, ... 2^15.
In binary, these values are 0...0001, 0...0010, 0100, etc., so twoToThe[i] only has bit i set.

You can test if a number has bit 2 set by ANDing it with twoToThe[2]:
0...11101       0...11001
0...00100 AND   0...00100 AND
---------       ---------
0...00100       0...00000
If the bit is set, the result will be non-zero.

The bit(x, i) function needs to do this AND operation and return true it the result of the and is 0.

Note that ~(x & twoToThe[i]) does not return true or false because ~ is bit-wise NOT.

--Mark
Reply | Threaded
Open this post in threaded view
|

Re: How should I utilize 'twoToThe[i]'

Ju Se Hoon
I confused "bit-shifting" with "bit-wise operation". Now It all makes sense now.

As always, thanks!