Skip to content

Instantly share code, notes, and snippets.

@pdu
Created February 21, 2013 14:18
Show Gist options
  • Save pdu/5005007 to your computer and use it in GitHub Desktop.
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
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