Dynamic Programming21 sections · 916 units
Open in Course

Simple Example - Subset Membership

Concrete usage

Let's ground those bit operations with a concrete example. Suppose you have n=4n = 4 elements labeled 0,1,2,30, 1, 2, 3. The mask 1313 in decimal equals 11011101 in binary.

Reading right to left: bit 00 is 11 (element 00 included), bit 11 is 00 (element 11 excluded), bit 22 is 11 (element 22 included), bit 33 is 11 (element 33 included).

So mask 1313 represents the subset {0,2,3}\{0, 2, 3\}. Check if element 22 is in the subset: (13>>2)&1=(1101>>2)&1=11&1=1(13 >> 2) \& 1 = (1101 >> 2) \& 1 = 11 \& 1 = 1. Yes, it's included. Check element 11: (13>>1)&1=110&1=0(13 >> 1) \& 1 = 110 \& 1 = 0. Not included. These operations become automatic with practice.