This is my first article on getting started. I would like to share some interesting problems about bit operation encountered in the previous brush questions

1,10 wu dalang drink medicine problem

Topic:

Said there were 1,000 bottles of DDVP, but only one was toxic. Now there are 10 rats to test, ask how to give Big Lang drink medicine can be the fastest to detect which bottle toxic.

Ideas:

This is a common quiz question. A lot of puzzles have to do with numbers. 1000 is the first thing you know, it’s a little bit less than 1024. Coincidentally, two to the tenth corresponds to ten mice.

Answer:

The 1000 bottles of medicine were numbered 1-1000. Then, 10 mice were allowed to stand obediently in a fixed position on a line to simulate 10 positions. And then for the drug numbered X, which can’t be greater than 10, every one of the bits in x gets a bite. Something like this:

'mouses:,9,8,7,6,5,4,3,2,1 [10]
x==1; x==0b0000000001;// If the last digit is 1, let the last mouse take a bite. x==100; x==0b0001100100;// From the right, the third, sixth and seventh bits are all 1, then the corresponding numbered mouse is given the whole bite.// After drinking all 1000 bottles, wait for the poison to spread.
// if the last mouse to die is 3,6,7, then the number 100 can be reversed, and the drug numbered 100 is poisonous.

Copy the code
// Enter mouses =list(range(10))
for i in range(1.1001):
    index=0
    while i:
        if i&1:
            mouses[index].drink(i)
        i>>1
        index+=1

res =0
for k,v in enumerate(mouses):
    if v.isdead():
    	res=res|1<<k
return res 

Copy the code

summary

Finally, 400 words. Novice entry, if there is an error please forgive me.