Skip to content

Instantly share code, notes, and snippets.

@pdu
Created January 6, 2013 14:46
Show Gist options
  • Select an option

  • Save pdu/4467660 to your computer and use it in GitHub Desktop.

Select an option

Save pdu/4467660 to your computer and use it in GitHub Desktop.
Divide two integers without using multiplication, division and mod operator. http://leetcode.com/onlinejudge
class Solution {
public:
int divide(int dividend_, int divisor_) {
long long dividend = dividend_, divisor = divisor_;
int flag = 1;
if (dividend < 0) {
flag *= -1;
dividend = -dividend;
}
if (divisor < 0) {
flag *= -1;
divisor = - divisor;
}
long long f[50], g[50];
int n = 1;
for (n = 1; ; ++n) {
if (n == 1) {
f[1] = divisor;
g[1] = 1;
}
else {
f[n] = f[n - 1] + f[n - 1];
g[n] = g[n - 1] + g[n - 1];
}
if (dividend - f[n] < f[n])
break;
}
int ret = 0;
for (int i = n; i >= 1; --i)
if (dividend >= f[i]) {
dividend -= f[i];
ret += g[i];
}
return ret * flag;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment