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; //二分前与二分后的中值
                    }
                }
            }
        }
    };
  • 相关阅读:
    UVA 254 Towers of Hanoi
    UVA 701 The Archeologists' Dilemma
    UVA 185 Roman Numerals
    UVA 10994 Simple Addition
    UVA 10570 Meeting with Aliens
    UVA 306 Cipher
    UVA 10160 Servicing Stations
    UVA 317 Hexagon
    UVA 10123 No Tipping
    UVA 696 How Many Knights
  • 原文地址:https://www.cnblogs.com/hlwyfeng/p/4536737.html
Copyright © 2011-2022 走看看