What is wrong in the code

You are not storing the res when ans==n. Store it before you break the loop.


again coming wrong ans

It is not always possible to get ans==n. For example, sqrt(8)=2. So you should also store answer when you do s=mid+1, ans=mid;

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.