[][src]Function leetcode_for_rust::cd0050_powx_n::my_pow

pub fn my_pow(x: f64, n: i64) -> f64

Solutions

Approach 1: Iteration

  • Time complexity: O(logn)

  • Space complexity: O(1)

  • Runtime: 0 ms

  • Memory: 2.4 MB

impl Solution {
    pub fn my_pow(x: f64, n: i32) -> f64 {
        let mut ln = n as i64;
        let mut pow = 1f64;
        let mut current = x;

        if ln < 0 {
            current = 1f64 / current;
            ln = -ln;
        }

        while ln > 0 {
            if ln & 1 == 1 { pow *= current; }
            current *= current;
            ln >>= 1;
        }
        pow
    }
}

Approach 2: Recursion

  • Time complexity: O(logn)

  • Space complexity: O(1)

impl Solution {
    pub fn my_pow(mut x: f64, mut n: i64) -> f64 {
        if n < 0 {
            x = 1.0 / x;
            n = -n;
        }
        if n == 0 { return 1.0; }
        let half = my_pow(x, n/2);
        if n & 1 == 0 {
            return half * half;
        } else {
            return half * half * x;
        }
    }
}