Created
November 8, 2014 17:56
-
-
Save wszdwp/2f0be36c867ffe41df67 to your computer and use it in GitHub Desktop.
Divide two integers without using multiplication, division and mod operator.
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
| public class Solution { | |
| public int divide(int dividend, int divisor) { | |
| //http://www.lifeincode.net/programming/leetcode-divide-two-integers-java/ | |
| long p = Math.abs((long)dividend); | |
| long q = Math.abs((long)divisor); | |
| int ret = 0; | |
| while (p >= q) { | |
| int counter = 0; | |
| while (p >= (q << counter)) { | |
| counter++; | |
| } | |
| ret += 1 << (counter - 1); | |
| p -= q << (counter - 1); | |
| } | |
| if ((dividend > 0 && divisor > 0) || (dividend < 0 && divisor < 0)) | |
| return ret; | |
| else | |
| return -ret; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment