Playing with bits

I think the approach is correct but this code gives me error of time limit exceed please help