aboutsummaryrefslogtreecommitdiff
path: root/divide_2_int.py
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2025-01-07 16:53:21 +0100
committerJack Sangdahl <[email protected]>2025-01-07 16:53:21 +0100
commit8a2b42fc8d607c983f5ce0f746253441fe7c38c4 (patch)
treef0e97dd4df910249429f516b97f60c8261d242a9 /divide_2_int.py
parentf456a519266258e8f392e183bc9e1bc399942dca (diff)
downloadleetcode-8a2b42fc8d607c983f5ce0f746253441fe7c38c4.tar.gz
leetcode-8a2b42fc8d607c983f5ce0f746253441fe7c38c4.zip
29. divide two integers
Diffstat (limited to 'divide_2_int.py')
-rw-r--r--divide_2_int.py32
1 files changed, 32 insertions, 0 deletions
diff --git a/divide_2_int.py b/divide_2_int.py
new file mode 100644
index 0000000..8439a1b
--- /dev/null
+++ b/divide_2_int.py
@@ -0,0 +1,32 @@
+# 29. Divide Two Integers
+
+"""
+Given two integers 'dividend' and 'divisor', divide two integers without
+using multiplication, division, or mod operations. the integer division
+should truncate toward zero, which means losing its fractional part. for
+example, 8.345 would be truncated to 8. return the quotient after dividing
+'dividend' by 'divisor'.
+"""
+
+
+class Solution(object):
+ def divide(self, dividend, divisor):
+ """
+ :type dividend: int
+ :type divisor: int
+ :rtype: int
+ """
+ if dividend == -2147483648 and divisor == -1:
+ return 2147483647
+ dvd, dvs, ans = abs(dividend), abs(divisor), 0
+ for i in range(32)[::-1]:
+ if (dvd >> i) - dvs >= 0:
+ ans += 1 << i
+ dvd -= dvs << i
+ return ans if (dividend > 0) == (divisor > 0) else -ans
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.divide(dividend=10, divisor=3))
+ print(obj.divide(dividend=7, divisor=-3))