[][src]Function leetcode_for_rust::cd0069_sqrtx::my_sqrt_f64

pub fn my_sqrt_f64(x: i32, precision: f64) -> f64

Solutions for f64

Approach 1: Binary Search

  • Time complexity: log(n)

  • Space complexity: log(n)

  • Runtime: 0 ms

  • Memory: 2.4 MB

impl Solution {
    fn my_sqrt_f64(x: i32, precision: f64) -> f64 {
        if x == 0 || x == 1 { return x as f64; }

        let mut left = 0f64;
        let mut right = x as f64;
        let mut res = 0f64;

        while left <= right {
            let mid: f64 = (right - left) / 2f64 + left;
            if (right - left).abs() < precision { return mid; }
            if mid > x as f64 / mid {
                right = mid;
            } else {
                left = mid;
                res = mid
            }
        }
        res
    }
}

Approach 2: Newton's Method

  • Time complexity: 𝑙𝑜𝑔2(𝑁)

  • Space complexity:

  • Runtime: 0 ms

  • Memory: 2.4 MB

impl Solution {
    pub fn my_sqrt_f64(x: i32) -> f64 {
        if x == 0 { return x as f64; }

        let x = x as f64;
        let mut r = x;
        while r > x / r {
            r = (r + x / r) / 2.0;
        }
        r
    }
}