Created
February 21, 2013 14:18
-
-
Save pdu/5005007 to your computer and use it in GitHub Desktop.
Divide two integers without using multiplication, division and mod operator. http://leetcode.com/onlinejudge#question_29
This file contains 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
long long f[32]; | |
long long g[32]; | |
class Solution { | |
public: | |
int divide(int dd, int dr) { | |
long long divisor = dr, dividend = dd; | |
int flag = 1; | |
if (divisor < 0) { | |
divisor = -divisor; | |
flag *= -1; | |
} | |
if (dividend < 0) { | |
dividend = -dividend; | |
flag *= -1; | |
} | |
f[0] = divisor; | |
g[0] = 1; | |
int n = 0; | |
while (dividend - f[n] >= f[n]) { | |
n++; | |
f[n] = f[n - 1] + f[n - 1]; | |
g[n] = g[n - 1] + g[n - 1]; | |
} | |
long long ans = 0; | |
for (int i = n; i >= 0; --i) { | |
if (dividend >= f[i]) { | |
ans += g[i]; | |
dividend -= f[i]; | |
} | |
} | |
return ans * flag; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment