Created
February 23, 2020 22:09
-
-
Save wushbin/3ccdc3886d7d6aef6bb42a305170aa08 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| **/ | |
| class Solution { | |
| public int divide(int dividend, int divisor) { | |
| if (dividend == Integer.MIN_VALUE && divisor == -1) { | |
| return Integer.MAX_VALUE; | |
| } | |
| if (divisor == 1) { | |
| return dividend; | |
| } | |
| int r = Math.abs(dividend); // abs(Integer.MIN_VALUE) -> Integer.MIN_VALUE | |
| int l = Math.abs(divisor); | |
| int sign = 0; | |
| if (dividend > 0 && divisor > 0 || dividend < 0 && divisor < 0) { | |
| sign = 1; | |
| } else { | |
| sign = -1; | |
| } | |
| int result = 0; | |
| while(r - l >= 0) { | |
| int i = 1; // bit move | |
| while( r - (l << i) >= 0) { | |
| i ++; | |
| } | |
| result += (1 << (i - 1)); // multiplier | |
| r -= (l << (i - 1)); | |
| } | |
| return sign == 1 ? result : -result; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment