zoukankan      html  css  js  c++  java
  • Leetcode Sqrt(int x) java

    题目

    Implement int sqrt(int x).

    Compute and return the square root of x.

    题意:本题是要找一个大于0的整数的开方之后的整数结果,如果有整数结果则返回该结果,若没有整数结果则返回最接近的整数值。因为x>=0,所以求的解肯定在0和x之间,故这里可以使用二分查找来查找结果。因为mid*mid的值可能大于int的最大值,所以使用long来保存mid值。

    代码为:

    public class Solution {
        public int mySqrt(int x) {  //因为是求一个整数,所以可以使用二分查找
            int low =0;
            int high=x;
            long mid=(low+high)/2;
            while(low<=high){
                if(mid*mid>x){
                    high=(int) mid-1;
                    mid=(low+high)/2;
                }else if(mid*mid<x){
                    low=(int) mid+1;
                    mid=(low+high)/2;
                }else{
                    System.out.println(mid);
                    return (int) mid;
                };
            }
            System.out.println(high);
            return high;
        }
    }
    

      

  • 相关阅读:
    开源收集
    理财
    MSSQL
    MAC-Python
    设计模式
    数据分析
    wkhtmltopdf是一个使用webkit网页渲染引擎开发的用来将 html转成 pdf的工具
    ETL
    MQ
    Java 资源
  • 原文地址:https://www.cnblogs.com/271934Liao/p/6892858.html
Copyright © 2011-2022 走看看