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

    examination questions

    Implement int sqrt(int x).

    Compute and return the square root of x.

    Example

    sqrt(3) = 1

    sqrt(4) = 2

    sqrt(5) = 2

    sqrt(10) = 3

    Challenge

    O(log(x))


    解题代码

    class Solution {
    public:
        /**
        * @param x: An integer
        * @return: The sqrt of x
        */
        int sqrt(int x) {
    
            if (x == 1){
                return 1;
            }
    
            long long int temp = x / 2;
            int deposit;
            while (true){
                if (temp * temp > x){
                    deposit = temp;
                    temp = temp / 2;
                }
                else{
                    if ((temp + 1)*(temp + 1) > x){
                        return temp;
                    }
                    else{
                        temp = (deposit + temp) / 2;
                    }
                }
            }
        }
    };

    算法分析

    使用二分法,给定一个要求的数,然后分半,若该数的平方大于给定的数,则对该数进行平分,如果平分后的平方小于给定的数,那么取该数与平分前的数的中数进行平方,每一次平方后如果该数是大于给定的数的,那么检测与该数小1的数的平方是否小于给定的数,如果是,那么该数为结果。

    代码解析

    class Solution {
    public:
        /**
        * @param x: An integer
        * @return: The sqrt of x
        */
        int sqrt(int x) {
    
            if (x == 1){ //如果为1,那么直接得出结果
                return 1;
            }
    
            long long int temp = x / 2; //二分
            int deposit; //用于二分前的值,存放
            while (true){
                if (temp * temp > x){ //大于就二分
                    deposit = temp; //存放
                    temp = temp / 2; //二分
                }
                else{
                    if ((temp + 1)*(temp + 1) > x){ //如果+1的平方大于x的话,那么就是该值
                        return temp;
                    }
                    else{
                        temp = (deposit + temp) / 2; //二分前与二分后的中值
                    }
                }
            }
        }
    };
  • 相关阅读:
    快速排序
    C# String.Format
    理解C++ static
    程序地址空间
    map的实现
    【S4】使用empty()而不是判断size()是否为0
    RHEL6.4 NFS文件共享服务器搭建
    使用UDEV绑定ASM多路径磁盘
    MySQL的启动程序
    [ERROR] Fatal error: Please read "Security" section of the manual to find out how to run mysqld as root!
  • 原文地址:https://www.cnblogs.com/hlwyfeng/p/4536737.html
Copyright © 2011-2022 走看看