首页 > 代码库 > Leetcode-Sqrt(x)
Leetcode-Sqrt(x)
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)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。