首页 > 代码库 > Leetcode 69. Sqrt(x) 求整数根 in Java

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