From eb01337fac0a93573856ca81e6fd28953ba1dc1f Mon Sep 17 00:00:00 2001 From: Lanre Adedara Date: Mon, 22 Jul 2024 06:52:11 +0100 Subject: [PATCH] feat: add swift implementation to lcof2 problem: No.072 --- .../README.md" | 23 +++++++++++++++++++ .../Solution.swift" | 18 +++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 "lcof2/\345\211\221\346\214\207 Offer II 072. \346\261\202\345\271\263\346\226\271\346\240\271/Solution.swift" diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 072. \346\261\202\345\271\263\346\226\271\346\240\271/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 072. \346\261\202\345\271\263\346\226\271\346\240\271/README.md" index e5a3f00d1894b..c1532de5315a2 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 072. \346\261\202\345\271\263\346\226\271\346\240\271/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 072. \346\261\202\345\271\263\346\226\271\346\240\271/README.md" @@ -160,6 +160,29 @@ public class Solution { } ``` +#### Swift + +```swift +class Solution { + func mySqrt(_ x: Int) -> Int { + if x == 0 { + return 0 + } + var left = 0 + var right = x + while left < right { + let mid = (left + right + 1) / 2 + if mid <= x / mid { + left = mid + } else { + right = mid - 1 + } + } + return left + } +} +``` + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 072. \346\261\202\345\271\263\346\226\271\346\240\271/Solution.swift" "b/lcof2/\345\211\221\346\214\207 Offer II 072. \346\261\202\345\271\263\346\226\271\346\240\271/Solution.swift" new file mode 100644 index 0000000000000..cbf73f89238e0 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 072. \346\261\202\345\271\263\346\226\271\346\240\271/Solution.swift" @@ -0,0 +1,18 @@ +class Solution { + func mySqrt(_ x: Int) -> Int { + if x == 0 { + return 0 + } + var left = 0 + var right = x + while left < right { + let mid = (left + right + 1) / 2 + if mid <= x / mid { + left = mid + } else { + right = mid - 1 + } + } + return left + } +}