-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0029-divide-two-integers.c
More file actions
40 lines (36 loc) · 936 Bytes
/
0029-divide-two-integers.c
File metadata and controls
40 lines (36 loc) · 936 Bytes
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/*
29. Divide Two Integers
Submitted: March 3, 2026
Runtime: 0 ms (beats 100.00%)
Memory: 9.01 MB (beats 22.07%)
*/
uint32_t udiv32(uint32_t a, uint32_t b) {
if (b > a) {
return 0;
} else if (a == b) {
return 1;
} else {
uint32_t res = 0;
uint8_t pos = __builtin_clz(b) - __builtin_clz(a);
do {
uint32_t shifted = b << pos;
if (a >= shifted) {
a -= shifted;
res += 1U << pos;
}
} while (pos-- != 0);
return res;
}
}
int divide(int a, int b) {
bool aSign = a < 0, bSign = b < 0;
uint32_t ua = aSign ? -(uint32_t)a : a, ub = bSign ? -(uint32_t)b : b;
uint32_t ures = udiv32(ua, ub);
bool resSign = aSign ^ bSign;
// negative
if (resSign) {
return ures > 2147483648 ? -2147483648 : -ures;
} else {
return ures > 2147483647 ? 2147483647 : ures;
}
}