LeetCode - Algorithms
  • Introduction
  • 1. Two Sum
  • 2. Add Two Numbers
  • 3. Longest Substring Without Repeating Characters
  • 4. Median of Two Sorted Arrays
  • 5. Longest Palindromic Substring
  • 6. ZigZag Conversion
  • 7. Reverse Integer
  • 8. String to Integer (atoi)
  • 9. Palindrome Number
  • 10. Regular Expression Matching
  • 11. Container with Most Water
  • 12. Integer to Roman
  • 13. Roman to Integer
  • 14. Longest Common Prefix
  • 15. 3Sum
  • 16. 3Sum Closest
  • 17. Letter Combinations of a Phone Number
  • 18. 4Sum
  • 19. Remove Nth Node From End of List
  • 20. Valid Parentheses
  • 21. Merge Two Sorted Lists
  • 22. Generate Parentheses
  • 23. Merge k Sorted Lists
  • 24. Swap Nodes in Pairs
  • 25. Reverse Nodes in k-Group
  • 26. Remove Duplicates from Sorted Array
  • 27. Remove Element
  • 28. Implement strStr()
  • 29. Divide Two Integers
  • 30. Substring with Concatenation of All Words
  • 31. Next Permutation
  • 32. Longest Valid Parentheses
  • 33. Search in Rotated Sorted Array
  • 34. Search for a Range
  • 35. Search Insert Position
  • 36. Valid Sudoku
  • 37. Sudoku Solver
  • 38. Count and Say
  • 39. Combination Sum
Powered by GitBook
On this page
  • Problem
  • Analysis
  • Code

29. Divide Two Integers

Problem

Divide two integers without using multiplication, division and mod operator.

If it is overflow, return MAX_INT.

Related Topics:

Math Binary Search

Analysis

先通过移位来靠近目标数,再利用减法抵达。

Code

class Solution {

    fun divide(dividend: Int, divisor: Int): Int {

        if ((divisor == 0) || (dividend == Int.MIN_VALUE && divisor == -1)) {
            return Int.MAX_VALUE
        }

        val sign: Boolean = when {
            dividend < 0 && divisor < 0 -> true
            dividend > 0 && divisor > 0 -> true
            else -> false
        }
        val dividendL = Math.abs(dividend.toLong())
        val divisorL = Math.abs(divisor.toLong())
        var temp = divisorL

        var count: Long = 1
        while (dividendL > temp) {
            count = count.shl(1)
            temp = temp.shl(1)
        }

        while (dividendL < temp) {
            count--
            temp -= divisorL
        }

        return when {
            sign -> count.toInt()
            else -> 0 - count.toInt()
        }
    }
}
Previous28. Implement strStr()Next30. Substring with Concatenation of All Words

Last updated 6 years ago