首页 > 其他 > 详细

Sqrt(x)

时间:2016-07-10 13:59:53      阅读:244      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!