1. 程式人生 > 其它 >leetcode 69 求平方根

leetcode 69 求平方根

二分查詢,不過查詢過程中的判斷條件更細一些,比如會判斷mid以及mid+1的正確性,貼程式碼

class Solution {
public:
    int mySqrt(int x) 
    {
        if(x == 0)
        return 0;
        if(x == 1)
        return 1;
        long long x_temp = x;
        long left = 1;
        long right = x_temp-1;
        while(left<=right)
        {
            
long long mid = (left + right)/2; if(mid*mid == x_temp) return mid; else if(mid*mid > x_temp) { right = mid - 1; } else { if((mid+1)*(mid+1) > x_temp) return mid;
else if((mid+1)*(mid+1) == x_temp) return mid+1; else { left = mid + 1; } } } return 0; } };

牛頓迭代法,需要數學方面的推導,設定一個函式y =x^2 -c,C開根號值即為該函式正零點,然後通過每一點的切線與x軸的交點不斷逼近目標值。貼程式碼

 1 class Solution {
2 public: 3 int mySqrt(int x) 4 { 5 if(x == 0) 6 return 0; 7 double C = x; 8 double x0 = x; 9 while(1) 10 { 11 double x_temp = 0.5*(x0 + C/x0); 12 if(fabs(x_temp-x0)<1e-7) 13 break; 14 x0 = x_temp; 15 } 16 return x0; 17 } 18 };