1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| package com.demo.s69;
public class Solution { public int mySqrt(int x) { int l = 0; int r = x; int ret = 0; int mid = 0; while(l <= r) { mid = (l + r)/ 2; long tmp = (long)mid * mid; if(tmp == x) { return mid; } if(tmp <= x) { ret = mid; l = mid + 1; } else { r = mid - 1; } } return ret; } }
|