Created
January 6, 2013 14:46
-
-
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
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_) { | |
| 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