[InterviewBit] Divide Integers

Divide Integers

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
int Solution::divide(int A, int B) {
if(B == 0) return INT_MAX;
long long sign = 1ll * A * B > 0 ? 1 : - 1;
long long rem = 0, res = 0;
long long a = A, b = B;
a = abs(a), b = abs(b);
if(a < b) return 0;
string s = to_string(a);
for(int i = 0; i < s.length(); i++) {
long long r = 0, rres = 0;
for(int j = 0; j < 10; j++) {
r += rem;
rres += res;
}
r += s[i] - '0';
while(r >= b) {
r -= b;
rres += 1;
}
rem = r;
res = rres;
}

return sign * res >= INT_MAX ? INT_MAX : sign * res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/30/PS/interviewbit/divide-integers/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.