Divide two integers without using multiplication, division and mod operator.ide
If it is overflow, return MAX_INT.spa
1 class Solution { 2 public: 3 int divide(int dividend, int divisor) { 4 if (!divisor) return (dividend >= 0 ? INT_MAX : INT_MIN); 5 if ((dividend == INT_MIN) && (divisor == -1)) return INT_MAX; 6 7 bool isNeg = false; 8 if (((dividend > 0) && (divisor < 0)) || ((dividend < 0) && (divisor > 0))){ 9 isNeg = true; 10 } 11 12 unsigned long long dvd = abs((long long)(dividend)); 13 unsigned long long dvs = abs((long long)(divisor)); 14 unsigned long long dvs_orig = dvs; 15 16 int res = 0; 17 int i = 0; 18 19 while (dvd >= (dvs << i)) i++; 20 21 while (dvd >= dvs_orig){ 22 if (dvd >= dvs << i){ 23 dvd -= dvs << i; 24 res += 1 << i; 25 } 26 i--; 27 } 28 29 return (isNeg ? (0 - res) : (res)); 30 } 31 };