• 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;
        }
    }
    

      

  • 相关阅读:
    Tomcat虚拟目录的映射方式
    Linux常用命令
    java断点调试
    破解MyEclipse
    JS判断浏览器
    css3 box-sizing详解。
    this-使用call . apply
    this-内部函数
    this-对象方法调用
    this-纯函数
  • 原文地址:https://www.cnblogs.com/271934Liao/p/6892858.html
Copyright © 2020-2023  润新知