Logic behind SPOJ ASSIGN problem

I am trying to understand the solution here.I am able to understand the bitmask,but unable to understand the logic.Any one please explain the logic.

//