Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a691615

Browse files
29. Divide Two Integers
1 parent 4299298 commit a691615

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

‎29. Divide Two Integers.kt

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution {
2+
fun divide(dividend: Int, divisor: Int): Int {
3+
if (dividend == Integer.MIN_VALUE && divisor == -1) {
4+
return Integer.MAX_VALUE
5+
}
6+
var num = abs(dividend.toLong())
7+
var divisor_ = abs(divisor.toLong())
8+
var res = 0L
9+
while (num >= divisor_) {
10+
var multi = 1L
11+
var times = divisor_
12+
while (times < num) {
13+
times = times shl 1
14+
multi = multi shl 1
15+
}
16+
if (times > num) {
17+
multi = multi shr 1
18+
times = times shr 1
19+
}
20+
res += multi
21+
num -= times
22+
}
23+
if ((dividend > 0) xor (divisor > 0)) {
24+
res = -res
25+
}
26+
return res.toInt()
27+
}
28+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /