diff --git a/README.md b/README.md index d28957b..36c87c7 100644 --- a/README.md +++ b/README.md @@ -249,6 +249,7 @@ they contain enough code which describes implementation in a natural way. | Java интервью 11 | [Youtube](https://youtu.be/zufbVgdBCAI) | - | | Java интервью 12 | [Youtube](https://youtu.be/PD41epg_pT4) | - | | Функциональные тесты REST API с помощью Spock | [Youtube](https://youtu.be/GK5y3oA3qfM) | - | +| Вычисление квадратного корня вавилонским методом (leetcode) | [Youtube](https://youtu.be/41zAzebmOuc) | [Code](src/main/java/by/andd3dfx/numeric/SquareRootBabylon.java) | ## Materials & notes diff --git a/src/main/java/by/andd3dfx/numeric/SquareRootBabylon.java b/src/main/java/by/andd3dfx/numeric/SquareRootBabylon.java new file mode 100644 index 0000000..f7037df --- /dev/null +++ b/src/main/java/by/andd3dfx/numeric/SquareRootBabylon.java @@ -0,0 +1,37 @@ +package by.andd3dfx.numeric; + +/** + *
+ * Task description
+ *
+ * Given a non-negative integer x, return the square root of x rounded down to the nearest integer.
+ * The returned integer should be non-negative as well.
+ * You must not use any built-in exponent function or operator.
+ *     For example, do not use pow(x, 0.5) in c++ or x ** 0.5 in python.
+ *
+ * Example 1:
+ *   Input: x = 4
+ *   Output: 2
+ *   Explanation: The square root of 4 is 2, so we return 2.
+ *
+ * Example 2:
+ *   Input: x = 8
+ *   Output: 2
+ *   Explanation: The square root of 8 is 2.82842...,
+ *   and since we round it down to the nearest integer, 2 is returned.
+ * 
+ * + * @see Video solution + */ +public class SquareRootBabylon { + + public static int mySqrt(int x) { + double old = x; + double root = x; + do { + old = root; + root = 0.5 * (root + x / root); + } while (Math.abs(root - old) >= 1); + return (int) root; + } +} diff --git a/src/test/java/by/andd3dfx/numeric/SquareRootBabylonTest.java b/src/test/java/by/andd3dfx/numeric/SquareRootBabylonTest.java new file mode 100644 index 0000000..369abef --- /dev/null +++ b/src/test/java/by/andd3dfx/numeric/SquareRootBabylonTest.java @@ -0,0 +1,22 @@ +package by.andd3dfx.numeric; + +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class SquareRootBabylonTest { + + @Test + public void mySqrt() { + assertThat(SquareRootBabylon.mySqrt(1)).isEqualTo(1); + assertThat(SquareRootBabylon.mySqrt(2)).isEqualTo(1); + assertThat(SquareRootBabylon.mySqrt(3)).isEqualTo(1); + assertThat(SquareRootBabylon.mySqrt(4)).isEqualTo(2); + assertThat(SquareRootBabylon.mySqrt(5)).isEqualTo(2); + assertThat(SquareRootBabylon.mySqrt(8)).isEqualTo(2); + assertThat(SquareRootBabylon.mySqrt(9)).isEqualTo(3); + assertThat(SquareRootBabylon.mySqrt(624)).isEqualTo(24); + assertThat(SquareRootBabylon.mySqrt(625)).isEqualTo(25); + assertThat(SquareRootBabylon.mySqrt(789)).isEqualTo(28); + } +}