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 {}
3333// Zero point: (root^2 + n) / (2 * root)
3434impl Solution {
3535 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 ;
4343 }
44- root = new_root ;
44+ size -= half ;
4545 }
46- root . trunc ( ) as i32
46+ base
4747 }
4848}
4949
@@ -60,7 +60,6 @@ mod tests {
6060 assert_eq ! ( Solution :: my_sqrt( 17 ) , 4 ) ;
6161 assert_eq ! ( Solution :: my_sqrt( 81 ) , 9 ) ;
6262 assert_eq ! ( Solution :: my_sqrt( 82 ) , 9 ) ;
63- assert_eq ! ( Solution :: my_sqrt( 100480576 ) , 10024 ) ;
6463 assert_eq ! ( Solution :: my_sqrt( 100480577 ) , 10024 ) ;
6564 assert_eq ! ( Solution :: my_sqrt( 100480575 ) , 10023 ) ;
6665 assert_eq ! ( Solution :: my_sqrt( 100480575 ) , 10023 ) ;
You can’t perform that action at this time.
0 commit comments