From fa17e52fc02fefb67dae5a7391f417ff0bcf28d0 Mon Sep 17 00:00:00 2001 From: Lanre Adedara Date: Thu, 30 May 2024 08:25:17 +0100 Subject: [PATCH] Swift implementation for LCOF2 001 --- .../README.md" | 30 +++++++++++++++++++ .../Solution.swift" | 25 ++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 "lcof2/\345\211\221\346\214\207 Offer II 001. \346\225\264\346\225\260\351\231\244\346\263\225/Solution.swift" diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 001. \346\225\264\346\225\260\351\231\244\346\263\225/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 001. \346\225\264\346\225\260\351\231\244\346\263\225/README.md" index a3fd364995bde..f8270967ee91b 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 001. \346\225\264\346\225\260\351\231\244\346\263\225/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 001. \346\225\264\346\225\260\351\231\244\346\263\225/README.md" @@ -268,6 +268,36 @@ public class Solution { } ``` +#### Swift + +```swift +class Solution { + func divide(_ a: Int, _ b: Int) -> Int { + if b == 1 { + return a + } + if a == Int32.min && b == -1 { + return Int(Int32.max) + } + let sign = (a > 0 && b > 0) || (a < 0 && b < 0) + var a = a > 0 ? -a : a + let b = b > 0 ? -b : b + var ans = 0 + while a <= b { + var x = b + var cnt = 1 + while x >= (Int32.min >> 1) && a <= (x << 1) { + x <<= 1 + cnt <<= 1 + } + ans += cnt + a -= x + } + return sign ? ans : -ans + } +} +``` + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 001. \346\225\264\346\225\260\351\231\244\346\263\225/Solution.swift" "b/lcof2/\345\211\221\346\214\207 Offer II 001. \346\225\264\346\225\260\351\231\244\346\263\225/Solution.swift" new file mode 100644 index 0000000000000..af0df4bbf33c9 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 001. \346\225\264\346\225\260\351\231\244\346\263\225/Solution.swift" @@ -0,0 +1,25 @@ +class Solution { + func divide(_ a: Int, _ b: Int) -> Int { + if b == 1 { + return a + } + if a == Int32.min && b == -1 { + return Int(Int32.max) + } + let sign = (a > 0 && b > 0) || (a < 0 && b < 0) + var a = a > 0 ? -a : a + let b = b > 0 ? -b : b + var ans = 0 + while a <= b { + var x = b + var cnt = 1 + while x >= (Int32.min >> 1) && a <= (x << 1) { + x <<= 1 + cnt <<= 1 + } + ans += cnt + a -= x + } + return sign ? ans : -ans + } +} \ No newline at end of file