본문 바로가기
LeetCode

[LeetCode] 29. Divide Two Integers

by JungSeung 2023. 10. 27.
728x90

https://leetcode.com/

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.


Example 1:

nput: dividend = 10, divisor = 3
Output: 3
Explanation: 10/3 = 3.33333.. which is truncated to 3.

 

Example 2:

Input: dividend = 7, divisor = -3
Output: -2
Explanation: 7/-3 = -2.33333.. which is truncated to -2.

 

Constraints:

  • -2^31 <= dividend, divisor <= 2^31 - 1
  • divisor != 0

Solutions Code 1 :

var divide = function(dividend, divisor) {
    // 최대값 조건 처리
    if (dividend === -2147483648 && divisor === -1) return 2147483647

    let ans = 0, sign = 1

    // 부호 처리
    if (dividend < 0) dividend = -dividend, sign = -sign
    if (divisor < 0) divisor = -divisor, sign = -sign

    // 나눗셈 계산
    if (dividend === divisor) return sign
    for (let i = 0, val = divisor; dividend >= divisor; i = 0, val = divisor) {
        while (val > 0 && val <= dividend) val = divisor << ++i
        dividend -= divisor << i - 1, ans += 1 << i - 1
    }
    return sign < 0 ? -ans : ans
};

 

Solutions Code 2 :

var divide = function(dividend, divisor) {
    // 부호 처리
    const retIsNegative = Math.sign(divisor) !== Math.sign(dividend);
    dividend = Math.abs(dividend)
    divisor = Math.abs(divisor)
    
    let ret = 0
    // 나눗셈 수행
    while (divisor <= dividend) {
        let value = divisor
        let multiple = 1
        // 제곱수를 이용한 나눗셈
        while (value + value <= dividend) {
            value += value
            multiple += multiple
        }
        dividend = dividend - value
        ret += multiple
    }
    
    // 반환값이 32비트 최댓값을 초과하는 경우 처리
    if (ret > ((2**31) - 1)) {
        return retIsNegative ? -(2**31) : 2**31 - 1
    }
    return retIsNegative ? -ret : ret
};

 

 

출처 : https://leetcode.com/problemset/all/

 

Problems - LeetCode

Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

leetcode.com

 

728x90