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

    Implement int sqrt(int x).

    Compute and return the square root of x.

    Code:

    class Solution {
    public:
        int sqrt(int x) {
            int start=0;
            int end=x/2>std::sqrt(INT_MAX)?std::sqrt(INT_MAX):x/2+1;
            while(start<=end){
                int mid=(start+end)/2;
                if(x==mid*mid)
                    return mid;
                else if(mid*mid<x)
                    start=mid+1;
                else
                    end=mid-1;
            }
            return (start+end)/2;
        }
    };

    Analysis:
    According to Newton's Method(http://en.wikipedia.org/wiki/Newton's_method), we can use
     x_(k+1)=1/2(x_k+n/(x_k))
    to get the sqrt(x).

    class Solution {
    public:
        int sqrt(int x) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            if (x==0) {return 0;}
            if (x==1) {return 1;}
           
            double x0 = 1;
            double x1;
            while (true){
                x1 = (x0+ x/x0)/2;
                if (abs(x1-x0)<1){return x1;}
                x0=x1;
            }
             
        }
    };
  • 相关阅读:
    大于00
    today
    10
    面试题flask
    开发者日志
    7月22日一天学的东西
    资料
    3333
    2222
    1
  • 原文地址:https://www.cnblogs.com/winscoder/p/3414679.html
Copyright © 2011-2022 走看看