Leetcode 69. Sqrt(x) 求整数根 in Java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 69. Sqrt(x) 求整数根 in Java相关的知识,希望对你有一定的参考价值。

69. Sqrt(x)

 
  • Total Accepted: 109623
  • Total Submissions: 418262
  • Difficulty: Medium

Implement int sqrt(int x).

Compute and return the square root of x.

public class Solution {
    public int mySqrt(int x) {
        if(x==1) return 1;
        
        //注意此题返回值int,和sqrt返回值double不同
        double low=0;
        double high=x;
        
        while(low<high){
            double mid=(low+high)/2;
            
            if(Math.abs(mid*mid-x)<0.01){
             return (int)mid;
            }else if(mid*mid<x){
                low=mid;
            }else{
                high=mid;
            }
            
        }
        return (int)low;
    }
}

 

以上是关于Leetcode 69. Sqrt(x) 求整数根 in Java的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 69. Sqrt(x)

leetcode 69.x的平方根(Java 二分查找 easy)

LeetCode 69 _ Sqrt(x) 求平方根 (Easy)

LeetCode 69 Sqrt(x)

leetcode 69. x 的平方根(Sqrt(x))

LeetCode 69 Sqrt(x)