leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0029.cpp (1000B)


      1 class Solution {
      2   public:
      3     int divide(int dividend, int divisor) {
      4         if (divisor == INT_MIN) return dividend == INT_MIN;
      5         if (divisor == INT_MAX) {
      6             if (dividend == INT_MIN) return -1;
      7             if (dividend == INT_MAX) return 1;
      8             return 0;
      9         }
     10 
     11         if (divisor == 1) return dividend;
     12         if (divisor == -1) {
     13             if (dividend == INT_MIN) return INT_MAX;
     14             return -dividend;
     15         }
     16 
     17         int res = 0, sign = 1;
     18         if (divisor < 0) divisor = -divisor, sign = -sign;
     19         if (dividend < 0) {
     20             if (dividend == INT_MIN) dividend += divisor, res++;
     21             dividend = -dividend, sign = -sign;
     22         }
     23 
     24         while (dividend >= divisor) {
     25             long temp = divisor, count = 1;
     26             while (temp << 1 <= dividend) {
     27                 temp <<= 1;
     28                 count <<= 1;
     29             }
     30             dividend -= temp;
     31             res += count;
     32         }
     33         return sign * res;
     34     }
     35 };