码迷,mamicode.com
首页 > 其他好文 > 详细

Sqrt(x)

时间:2016-07-10 14:00:52      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

Implement int sqrt(int x).

Compute and return the square root of x.

Example

sqrt(3) = 1

sqrt(4) = 2

sqrt(5) = 2

sqrt(10) = 3

 1 class Solution {
 2     /**
 3      * @param x: An integer
 4      * @return: The sqrt of x
 5      */
 6     public int sqrt(int x) {
 7         long start = 0;
 8         long end = x;
 9 
10         while (start <= end) {
11             long mid = start + (end - start) / 2;
12             if (mid * mid == x) {
13                 return (int) mid;
14             } else if (mid * mid < x) {
15                 start = mid + 1;
16             } else {
17                 end = mid - 1;
18             }
19         }
20         return (int)(start - 1);  // we are looking for lower end.
21     }
22 }

or we can do it another way.

 1 class Solution {
 2     /**
 3      * @param x: An integer
 4      * @return: The sqrt of x
 5      */
 6     public int sqrt(int x) {
 7         long start = 0;
 8         long end = x;
 9 
10         while (start <= end) {
11             long mid = start + (end - start) / 2;
12             if (mid * mid == x) {
13                 return (int) mid;
14             } else if (mid * mid < x && (mid + 1) * (mid + 1) > x) {
15                 return (int) mid;
16             } else if (mid * mid < x) {
17                 start = mid + 1;
18             } else {
19                 end = mid - 1;
20             }
21         }
22         return -1;
23     }
24 }

 

Sqrt(x)

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5657455.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!