0

How should the following code be interpreted?

s = "";
my_arr = [1, 2, .....]
for i in range(len(my_arr)):
    for j in range(len(my_arr)):
        if (i & (1<<j)) != 0:
            s += str(my_arr[j])

I cannot understand the following syntax:

if (i & (1<<j))!=0
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
Amir H. Bagheri
  • 1,416
  • 1
  • 9
  • 17

1 Answers1

0

<< is a bitwise operator:

x << y

Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y.

example

x << y corresponds to x*(2**y).

If x=3 and y=4, x<<y is 3*(2**4)=3*16=48.

In your case, since x is 1, the inner for loop considers powers of 2 in that part of code.

sentence
  • 8,213
  • 4
  • 31
  • 40