首页 > 其他 > 详细

Leetcode-Sqrt(x)

时间:2014-11-17 01:37:52      阅读:273      评论:0      收藏:0      [点我收藏+]

Implement int sqrt(int x).

Compute and return the square root of x.

Analysis:

Using binary search to find the solution. However, what need to be consider is when x is large, some k=(begin+end)/2 may be overflow, as a result, we cannot get the right answer. When calculating k*k, we need cast k to (double) type.

Solution:

 1 public class Solution {
 2     public int sqrt(int x) {
 3         if (x==0 || x==1) return x;
 4         
 5         int z = x;
 6         int y = 1;
 7         int k = -1;
 8         while (true){
 9             k = y+(z-y)/2;
10             double temp = (double) k*(double)k;
11             if (temp==x) 
12                 return k;
13             else if (temp>x){
14                 z = k;
15                 continue;
16             } else if ((double)(k+1)*(double)(k+1)>x){
17                 return k;
18             } else {
19                 y = k;
20                 continue;
21             }
22         }
23 
24         
25     }
26 }

 

Leetcode-Sqrt(x)

原文:http://www.cnblogs.com/lishiblog/p/4102728.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!