Optimized bit-count logic as per comments