20240801 Finished

This commit is contained in:
jackfiled 2024-08-01 11:30:06 +08:00
parent dc662fe156
commit bc583588af
2 changed files with 48 additions and 1 deletions

View File

@ -190,4 +190,5 @@ mod p136_single_number;
mod p137_single_number_ii; mod p137_single_number_ii;
mod p201_bitwise_and_of_numbers_range; mod p201_bitwise_and_of_numbers_range;
mod p66_plus_one; mod p66_plus_one;
mod p172_factorial_trailing_zeroes; mod p172_factorial_trailing_zeroes;
mod p69_sqrtx;

46
src/problem/p69_sqrtx.rs Normal file
View File

@ -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));
}
}