jayati

Square root of a number

Feb 28th, 2023
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.48 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int mySqrt(int x) {
  4.         if (x == 0)
  5.             return x;
  6.         int first = 1, last = x;
  7.         while (first <= last) {
  8.             int mid = first + (last - first) / 2;
  9.             if (mid  == x / mid)
  10.                 return mid;
  11.             else if (mid > x / mid) {
  12.                 last = mid - 1;
  13.             }
  14.             else {
  15.                 first = mid + 1;
  16.             }
  17.         }
  18.         return last;
  19.        
  20.        
  21.     }
  22. };
Advertisement
Add Comment
Please, Sign In to add comment