File tree Expand file tree Collapse file tree 1 file changed +9
-10
lines changed Expand file tree Collapse file tree 1 file changed +9
-10
lines changed Original file line number Diff line number Diff line change @@ -33,17 +33,17 @@ pub struct Solution {}
33
33
// Zero point: (root^2 + n) / (2 * root)
34
34
impl Solution {
35
35
pub fn my_sqrt ( x : i32 ) -> i32 {
36
- if x < 2 { return x }
37
- let mut root = x as f64 ;
38
- loop {
39
- let new_root : f64 = ( root * root + x as f64 ) / ( 2.0 * root ) ;
40
- if root - new_root < 0.5 {
41
- root = new_root ;
42
- break ;
36
+ let mut size = x ;
37
+ let mut base = 1 ;
38
+ while size > 1 {
39
+ let half = size / 2 ;
40
+ let mid = base + half ;
41
+ if mid <= x / mid {
42
+ base = mid ;
43
43
}
44
- root = new_root ;
44
+ size -= half ;
45
45
}
46
- root . trunc ( ) as i32
46
+ base
47
47
}
48
48
}
49
49
@@ -60,7 +60,6 @@ mod tests {
60
60
assert_eq ! ( Solution :: my_sqrt( 17 ) , 4 ) ;
61
61
assert_eq ! ( Solution :: my_sqrt( 81 ) , 9 ) ;
62
62
assert_eq ! ( Solution :: my_sqrt( 82 ) , 9 ) ;
63
- assert_eq ! ( Solution :: my_sqrt( 100480576 ) , 10024 ) ;
64
63
assert_eq ! ( Solution :: my_sqrt( 100480577 ) , 10024 ) ;
65
64
assert_eq ! ( Solution :: my_sqrt( 100480575 ) , 10023 ) ;
66
65
assert_eq ! ( Solution :: my_sqrt( 100480575 ) , 10023 ) ;
You can’t perform that action at this time.
0 commit comments