Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Divide Two Integers #52

Closed
Tracked by #100
fkdl0048 opened this issue Oct 4, 2024 · 0 comments
Closed
Tracked by #100

Divide Two Integers #52

fkdl0048 opened this issue Oct 4, 2024 · 0 comments
Assignees
Labels
Milestone

Comments

@fkdl0048
Copy link
Owner

fkdl0048 commented Oct 4, 2024

class Solution {
public:
    int divide(int dividend, int divisor) {
        if (dividend == divisor) return 1;

        unsigned int ans = 0;
        int sign = 1;

        // Determine the sign of the result
        if ((dividend < 0) ^ (divisor < 0))
            sign = -1;

        // Convert both dividend and divisor to positive integers
        unsigned int n = abs(dividend), d = abs(divisor);

        // Perform the division
        while (n >= d) {
            int count = 0;
            while (n > (d << (count + 1)))
                count++;
            n -= d << count;
            ans += 1 << count;
        }

        // Handle overflow case
        if (ans == (1 << 31) && sign == 1) return INT_MAX;

        return sign * ans;
    }
};
  • 비트 연산이 너무 오랜만이라 헷갈린 문제.. 결국 솔루션을 봤다.
  • 핵심은 오버플로우 처리 방식으로 INT_MIN에 -1이 곱해지면 터지는 동작을 절대값으로 변환하여 처리한다고 보면 된다.
@fkdl0048 fkdl0048 mentioned this issue Oct 4, 2024
7 tasks
@fkdl0048 fkdl0048 self-assigned this Oct 4, 2024
@fkdl0048 fkdl0048 added this to Todo Oct 4, 2024
@github-project-automation github-project-automation bot moved this to Todo in Todo Oct 4, 2024
@fkdl0048 fkdl0048 added this to the LeetCode milestone Oct 4, 2024
@fkdl0048 fkdl0048 moved this from Todo to Two-Week Plan in Todo Oct 4, 2024
@fkdl0048 fkdl0048 closed this as completed Oct 5, 2024
@github-project-automation github-project-automation bot moved this from Two-Week Plan to Done in Todo Oct 5, 2024
@fkdl0048 fkdl0048 mentioned this issue Oct 15, 2024
47 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
Status: Done
Development

No branches or pull requests

1 participant