欣迪

出處: https://leetcode.com/problems/divide-two-integers/

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.7335 would 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:

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

Example 2:

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

Constraints:

  • -231 <= dividend, divisor <= 231 - 1
  • divisor != 0

這題其實沒什麼難度,主要在考驗正負數之間的進位問題。

/**
 * @param {number} dividend
 * @param {number} divisor
 * @return {number}
 */
var divide = function(dividend, divisor) {
  	// 除術和被除數任一為零時,進入狀況一
    if (dividend < 0 ^ divisor < 0) {
      	// 由於結果一定是負數,小數點吼的數字需要使用 Math.ceil
        return Math.max(Math.ceil(dividend / divisor), (-2) ** 31)
    } else {
      	// 正數時,只取整數
        return Math.min(Math.floor(dividend / divisor), 2** 31 - 1)
    }
};

先看 Math.floor 和 Math.ceil 的定義:

Math.floor() 函式會回傳小於等於所給數字的最大整數。
Math.ceil() 函式會回傳大於等於所給數字的最小整數。

當數字小於 0 時,會發生以下的情形 :

Math.floor(-2.1) 
// retrun -3

Math.floor(-2) 
// retrun -2

這是由於它的定義是回傳小於等於輸入數字的最大整數。 -3 小於 -2.1,因此 ,使用 Math.floor,會回應小於 -2.1 的最大整數 (-3),Math.ceil 則相反。

這題的陷阱就在於,它是要取得結果的整數部分,因此一但結果小於 0,就必須要特別注意這裡的變化。

訂閱 IT-Monk

訂閱最新文章的發布消息! 😚😚😚
Loading

作者介紹 - 欣迪

欣迪

從設計到寫程式,發現自己有追求前端技巧的自虐傾向。不斷的踩坑,再從坑裡爬出來,慢慢對攀岩有點心得。 目前在多間公司擔任網站設計顧問。 同時也是網站架設公司負責人。