넘치게 채우기

[LeetCode] 29. Divide Two Integers 본문

PS/LeetCode

[LeetCode] 29. Divide Two Integers

riveroverflow 2023. 5. 3. 00:31
728x90
반응형

https://leetcode.com/problems/divide-two-integers/description/

 

Divide Two Integers - LeetCode

Can you solve this real interview question? 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 it

leetcode.com

문제 유형 : 수학 / 자료형

난이도 : Medium

 

 

문제

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.

피제수 dividend와 제수 divisor 의 몫을 출력하라(소수점은 잘라서 반환하라)

32비트 범위의 정수인 int를 사용하는 것을 알아라. 몫이 2^31-1보다 커지면, 2^31-1을 반환하고, -2^31보다 작아지면, -2^31을 출력한다.

 

 

입력

두 개의 int형 정수 dividend, divisor 가 있다(-2^31 <= dividend, divisor <= 2^31 - 1, divisor != 0)

 

 

출력

몫을 int 범위 이내로 반환한다.

 

 

풀이

정수의 나눗셈이므로 몫의 절대값이 더 커질 경우는 없다. 그러므로 -2^31이 -1에 나눠져서 2^31이 되는 경우가 유일하게 범위를 나오는 경우다. 예외 처리는 이것만 해주면 된다. 몫은 int 와 int의 나눗셈이므로 어려울 게 없다.

 

 

코드(C++)

class Solution {
public:
    int divide(int dividend, int divisor) {
        if(dividend == INT_MIN && divisor == -1){
            return INT_MAX;
        }
        int result = dividend / divisor;
        return result;
    }
};
728x90
반응형