[Leetcode 85] 69 Sqrt(x)

Problem:

Implement int sqrt(int x).

Compute and return the square root of x.

 

Analysis:

If we simply use the naive algorithm to go through all the numbers from 0 until the square root, it will exceed the time limit. The hero is binary search.

We want such a number between 0 and n inclusively that x*x <= n and  (x+1)*(x+1) > n. Not exactly x*x = n because its the integer square root. With this exit condition, we can easily use binary search to get the final result.

 

Code:

 1 class Solution {
 2 public:
 3     int sqrt(int x) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         int s = 0, e = x;
 7         
 8         while (s <= e) {
 9             long long mid = (s + e) / 2, sq = mid * mid;
10             
11             if (sq <= x && (mid+1) * (mid+1) > x)
12                 return (int) mid;
13             else if (sq > x)
14                 e = mid - 1;
15             else
16                 s = mid + 1;
17         }
18         
19         return -1;
20     }
21 };
View Code

 

posted on 2013-07-25 05:43  freeneng  阅读(236)  评论(0编辑  收藏  举报

导航