- Today
- Total
작심삼일
[LeetCode] 29 | Divide Two Integers | Python 본문
문제 링크: https://leetcode.com/problems/divide-two-integers/
문제
Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator.
The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2.
Return the quotient after dividing dividend by divisor.
Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [$-2^{31}$, $2^{31}-1$]. For this problem, if the quotient is strictly greater than $2^{31}-1$, then return $2^{31}-1$, and if the quotient is strictly less than $-2^{31}$, then return $-2^{31}$.
조건
- $-2^{31}$ <= dividend, divisor <= $2^{31}-1$
- divisor != 0
내 풀이
$2^{31}-1$보다 크면 $2^{31}-1$를, $-2^{31}$보다 작으면 $-2^{31}$로 바꾼다.
소숫점이 있을 때 이를 0이 가까운 방향으로 가야하므로, ans가 음수일 때는 ceil, 양수일 때는 floor를 사용한다.
ans가 0일 때는 0.0이 되므로 int로 리턴한다.
코드
class Solution:
def divide(self, dividend: int, divisor: int) -> int:
ans = dividend/divisor
if ans < -(2**31): ans = -(2**31)
elif ans > 2**31-1 : ans = 2**31-1
if ans < 0: ans = ceil(ans)
elif ans > 0: ans = floor(ans)
return int(ans)
'스터디 > 코테' 카테고리의 다른 글
[LeetCode] 88 | Merge Sorted Array | Python (0) | 2022.06.08 |
---|---|
[LeetCode] 867 | Transpose Matrix | Python (0) | 2022.06.02 |
[LeetCode] 191 | Number of 1 Bits | Python (0) | 2022.05.26 |
[LeetCode] 354 | Russian Doll Envelopes | Python (0) | 2022.05.25 |
[LeetCode] 474 | Ones and Zeros | Python (0) | 2022.05.23 |