29. divide two integers

o— layout : post title : “29. Divide Two Integers” category : algorithm[LeetCode] tags: [LeetCode] —

  • Source : Link
  • Author : Han
  • Date : 2022-03-02

Problems

Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator.

The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8, and -2.7335would be truncated to -2.

Return the quotient after dividing dividend by divisor.

Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, if the quotient is strictly greater than 231 - 1, then return 231 - 1, and if the quotient is strictly less than -231, then return -231.

Example 1:

1
2
3
4
Input: dividend = 10, divisor = 3
Output: 3
Explanation: 10/3 = 3.33333.. which is truncated to 3.

Example 2:

1
2
3
4
Input: dividend = 7, divisor = -3
Output: -2
Explanation: 7/-3 = -2.33333.. which is truncated to -2.

Solution

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
class Solution {
    fun divide(dividend: Int, divisor: Int): Int {
        return when {
            divisor == 1 -> dividend
            divisor == -1 && dividend == Int.MIN_VALUE -> Int.MAX_VALUE
            divisor == Int.MIN_VALUE && dividend == Int.MIN_VALUE -> 1
            else -> {
                var absDividend = Math.abs(dividend)
                val absDivisor = Math.abs(divisor)
                var result = 0
                while (absDividend - absDivisor >= 0) {
                    var shift = 0
                    while (absDividend - (absDivisor shl shift) >= 0 && absDivisor shl shift > 0) shift++

                    shift--
                    result += (1 shl shift)
                    absDividend -= (absDivisor shl shift)
                }
                return when {
                    dividend xor divisor >= 0 -> result
                    else -> -result
                }
            }
        }
    }
}