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; //二分前与二分后的中值
                    }
                }
            }
        }
    };
  • 相关阅读:
    LeetCode-Read N Characters Given Read4 II
    LeetCode-One Edit Distance
    LeetCode-Palindrome Permutation II
    LeetCode- Longest Absolute File Path
    LeetCode-Strobogrammatic Number II
    LeetCode-Strobogrammatic Number
    LeetCode-Flatten 2D Vector
    LeetCode-Shortest Word Distance III
    LeetCode-Shortest Word Distance II
    Cookie/Session
  • 原文地址:https://www.cnblogs.com/hlwyfeng/p/4536737.html
Copyright © 2011-2022 走看看