1
+ /*
2
+ Link: https://leetcode.com/problems/divide-two-integers/
3
+
4
+ Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.
5
+
6
+ Return the quotient after dividing dividend by divisor.
7
+
8
+ The integer division should truncate toward zero, which means losing its fractional part. For example, truncate(8.345) = 8 and truncate(-2.7335) = -2.
9
+
10
+ Example 1:
11
+
12
+ Input: dividend = 10, divisor = 3
13
+ Output: 3
14
+ Explanation: 10/3 = truncate(3.33333..) = 3.
15
+ Example 2:
16
+
17
+ Input: dividend = 7, divisor = -3
18
+ Output: -2
19
+ Explanation: 7/-3 = truncate(-2.33333..) = -2.
20
+ Note:
21
+
22
+ Both dividend and divisor will be 32-bit signed integers.
23
+ The divisor will never be 0.
24
+ */
25
+
26
+ // Solution
27
+ // We subtract the sum of all powers of two less than the current dividend from it.
28
+ // and repeat the process untill dividend is less than divisor.
29
+
30
+ /*
31
+ TC = O(1)
32
+ SC = O(1)
33
+ */
34
+
35
+ class Solution {
36
+ public:
37
+ int divide (long long int dividend, long long int divisor) {
38
+
39
+ long long ans = 0 , temp = 1 ;
40
+
41
+ int flag = (divisor < 0 ^ dividend < 0 );
42
+
43
+ if (dividend == INT_MIN && divisor == -1 )
44
+ return INT_MAX;
45
+
46
+ if (dividend == INT_MIN && divisor == 1 )
47
+ return INT_MIN;
48
+
49
+ dividend = abs (dividend);
50
+ divisor = abs (divisor);
51
+
52
+ while (dividend >= divisor) {
53
+ long long int temp = 1 ;
54
+ ans += temp;
55
+ long long int div = divisor;
56
+ dividend -= divisor;
57
+ while (dividend >= divisor << 1 ) {
58
+ divisor <<= 1 ;
59
+ dividend = dividend - divisor;
60
+ temp <<= 1 ;
61
+
62
+ ans += temp;
63
+ }
64
+
65
+ divisor = div ;
66
+ }
67
+ if (flag)
68
+ return -ans;
69
+ return ans;
70
+ }
71
+ };
0 commit comments