diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 4272816..bbc0641 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -190,4 +190,5 @@ mod p136_single_number; mod p137_single_number_ii; mod p201_bitwise_and_of_numbers_range; mod p66_plus_one; -mod p172_factorial_trailing_zeroes; \ No newline at end of file +mod p172_factorial_trailing_zeroes; +mod p69_sqrtx; \ No newline at end of file diff --git a/src/problem/p69_sqrtx.rs b/src/problem/p69_sqrtx.rs new file mode 100644 index 0000000..09b6630 --- /dev/null +++ b/src/problem/p69_sqrtx.rs @@ -0,0 +1,46 @@ + +/** + * [69] Sqrt(x) + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn my_sqrt(x: i32) -> i32 { + // 牛顿迭代法 + if x == 0 { + return 0; + } + + let c = x as f64; + let mut x = x as f64; + + loop { + let xi = 0.5 * (x + c / x); + if (x - xi).abs() < 1e-7 { + break; + } + x = xi; + } + + return x as i32; + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_69() { + assert_eq!(0, Solution::my_sqrt(0)); + assert_eq!(1, Solution::my_sqrt(1)); + assert_eq!(1, Solution::my_sqrt(2)); + assert_eq!(2, Solution::my_sqrt(4)); + assert_eq!(2, Solution::my_sqrt(8)); + } +}