fork download
  1. #include <iostream>
  2. #include <climits>
  3. #include <cmath>
  4. #include <stdexcept>
  5. using namespace std;
  6.  
  7. pair<long long, long long> decompose(long long a, long long b) { // DONT MAKE a < b
  8. int k = 0; // decompose a to a/b = 2^k + d, d < 2^k
  9. while (b < a) {
  10. b <<= 1;
  11. k++;
  12. }
  13. if (b == a) return make_pair(k, 0);
  14. return make_pair(--k, a - (b>>1));
  15. }
  16.  
  17. int divide(int dvd, int dvs) {
  18. if (dvs == 0) throw overflow_error("Divide by zero exception");
  19. if (dvd == 0) return 0;
  20.  
  21. long long ldvd, ldvs;
  22. ldvd = abs((long long)dvd); ldvs = abs((long long)dvs);
  23. if (ldvd < ldvs) return 0;
  24.  
  25. long long ret = 0;
  26. pair<long long, long long> kb;
  27. do{
  28. kb = decompose(ldvd, ldvs);
  29. ret += 1 << kb.first;
  30. ldvd = kb.second;
  31. } while (kb.second >= ldvs);
  32. return ((dvd>>31) == (dvs>>31)) ? ret : (~ret + 1);
  33. }
  34.  
  35. int main() {
  36. cout << divide(1, -1) << endl;
  37. cout << divide(2147483647, 1) << endl;
  38. cout << divide(-1010369383, -2147483648 ) << endl;
  39. cout << divide(-2147483648, -1) << endl; // just for fun.
  40. // your code goes here
  41. return 0;
  42. }
Success #stdin #stdout 0s 3296KB
stdin
Standard input is empty
stdout
-1
2147483647
0
-2147483648