Slip and Slide


#1

So I've got the answer right after a few tries but I'm wondering, why is mask = 0b1 << n-1. Intuitively, I got to the correct answer but I want it to be clear. Let's say n = 2, does that mean that n-1 = 1 meaning we need to shift 0b1 to the left by one step?


#2

Shifting left is the same as multiplying by two, because each digit becomes worth twice as much
In base10 shifting left multiplies by 10

Here you're after a particular position, so since you start at the first position, how many more shifts do you need?

If you have 10 and want 1000, how many times do you need to multiply by 10?


#3

Thanks for replying! That way of thinking confused me a bit but I get what you're saying :smiley: I went over it yesterday and I the way I understand it is that if, for example, we want to shift it to the 10th position to the left we'll only need to move it 9 times because we already start at a value so if we moved it 10 places we'd get the 11th position to the left which is not what we want.


#4

You can rather easily write code to confirm that

n = 1

for _ in range(10):
    print('{:0>10b}'.format(n))
    n <<= 1

I did my best to make that look arcane :> (It's just bin() and left-padding with zeros, % for formatting ran out of favour so that's the new formatting style)

out:

0000000001
0000000010
0000000100
0000001000
0000010000
0000100000
0001000000
0010000000
0100000000
1000000000

#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.