LeetCode 69. Sqrt(x)

原题链接在这里:https://leetcode.com/problems/sqrtx/

题目:

Implement int sqrt(int x).

Compute and return the square root of x, where x is guaranteed to be a non-negative integer.

Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.

Example 1:

Input: 4
Output: 2

Example 2:

Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since 
             the decimal part is truncated, 2 is returned.

题解:

先找middle = (left + right)/2, middle^2 和 x 比较,比x小就在middle 和 right这段找,反之亦然。

Note:1. middle 要设为long, 否则middle * middle 可能overflow

2. while loop的条件是l<=r, 不是< e.g. x = 2

3. return 别忘了加cast

4. 即使这不是一个perfect square 也是返回right, 因为此时right就是那个较小的值.

Time Complexity: O(logx). Space: O(1).

AC Java:

 1 public class Solution {
 2     public int mySqrt(int x) {
 3         if(x<0){
 4             throw new IllegalArgumentException("Invalid input.");
 5         }
 6         
 7         long l = 0; 
 8         long r = x;
 9         while(l<=r){
10             long mid = l+(r-l)/2;
11             if(mid*mid > x){
12                 r = mid-1;
13             }else if(mid*mid < x){
14                 l = mid+1;
15             }else{
16                 return (int)mid;
17             }
18         }
19         return (int)r;
20     }
21 }

类似Pow(x, n)Valid Perfect Square

posted @ 2015-09-15 00:21  Dylan_Java_NYC  阅读(310)  评论(0编辑  收藏  举报