BiruLyu
6/6/2017 - 5:29 PM

367. Valid Perfect Square(Newton Method).java

/*
   float f = 2/3;
    System.out.println(f);  // Print 0.0

    f = (float)(2/3);
    System.out.println(f);  // Print 0.0

    f = (float)2/3;
    System.out.println(f);  // Print 0.6666667
*/


public class Solution {
    public boolean isPerfectSquare(int num) {
        if (num == 1) return true;
        int start = 1;
        int end = num / 2;
        while(start <= end) {
            int mid = start + (end - start) / 2;
            long temp = (long)mid * mid; //!!!!
            if (temp == num) {
                return true;
            } else if(temp > num) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
       return false; 
    }
}
    boolean isPerfectSquare(int num) {
      if (num < 1) return false;
      long t = num / 2;
      while (t * t > num) {
        t = (t + num / t) / 2;
      }
      return t * t == num;
    }



  //[1]: https://en.wikipedia.org/wiki/Newton%27s_method