From bc583588afd07d29d6c42bc7717d87099cdfcb58 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Thu, 1 Aug 2024 11:30:06 +0800 Subject: [PATCH] 20240801 Finished --- src/problem/mod.rs | 3 ++- src/problem/p69_sqrtx.rs | 46 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 src/problem/p69_sqrtx.rs 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)); + } +}