#include <iostream>
#include <climits>
#include <cmath>
#include <stdexcept>
using namespace std;
pair<long long, long long> decompose(long long a, long long b) { // DONT MAKE a < b
int k = 0; // decompose a to a/b = 2^k + d, d < 2^k
while (b < a) {
b <<= 1;
k++;
}
if (b == a) return make_pair(k, 0);
return make_pair(--k, a - (b>>1));
}
int divide(int dvd, int dvs) {
if (dvs == 0) throw overflow_error("Divide by zero exception");
if (dvd == 0) return 0;
long long ldvd, ldvs;
ldvd = abs((long long)dvd); ldvs = abs((long long)dvs);
if (ldvd < ldvs) return 0;
long long ret = 0;
pair<long long, long long> kb;
do{
kb = decompose(ldvd, ldvs);
ret += 1 << kb.first;
ldvd = kb.second;
} while (kb.second >= ldvs);
return ((dvd>>31) == (dvs>>31)) ? ret : (~ret + 1);
}
int main() {
cout << divide(1, -1) << endl;
cout << divide(2147483647, 1) << endl;
cout << divide(-1010369383, -2147483648 ) << endl;
cout << divide(-2147483648, -1) << endl; // just for fun.
// your code goes here
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8Y2xpbWl0cz4KI2luY2x1ZGUgPGNtYXRoPgojaW5jbHVkZSA8c3RkZXhjZXB0Pgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKcGFpcjxsb25nIGxvbmcsIGxvbmcgbG9uZz4gZGVjb21wb3NlKGxvbmcgbG9uZyBhLCBsb25nIGxvbmcgYikgeyAgICAgICAgLy8gRE9OVCBNQUtFIGEgPCBiCglpbnQgayA9IDA7ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC8vIGRlY29tcG9zZSBhIHRvIGEvYiA9IDJeayArIGQsIGQgPCAyXmsKCXdoaWxlIChiIDwgYSkgewoJCWIgPDw9IDE7CgkJaysrOwoJfQoJaWYgKGIgPT0gYSkgcmV0dXJuIG1ha2VfcGFpcihrLCAwKTsKCXJldHVybiBtYWtlX3BhaXIoLS1rLCBhIC0gKGI+PjEpKTsKfQoKaW50IGRpdmlkZShpbnQgZHZkLCBp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