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

LeetCode:Sqrt(x) 解题报告

时间:2015-01-02 23:35:53      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:

Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

SOLUTION 1:

参见:二分法总结,以及模板:http://t.cn/RZGkPQc

技术分享
 1 public class Solution {
 2     public int sqrt(int x) {
 3         if (x == 1 || x == 0) {
 4             return x;
 5         }
 6         
 7         int left = 1;
 8         int right = x;
 9         
10         while (left < right - 1) {
11             int mid = left + (right - left) / 2;
12             int quo = x / mid;
13             
14             if (quo == mid) {
15                 return quo;
16             // mid is too big    
17             } else if (quo < mid) {
18                 right = mid;
19             } else {
20                 left = mid;
21             }
22         }
23         
24         return left;
25     }
26 }
View Code

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/divide2/Sqrt.java

 

LeetCode:Sqrt(x) 解题报告

标签:

原文地址:http://www.cnblogs.com/yuzhangcmu/p/4198959.html

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