leetcode : Divide Two Integers
runtime 0 ms, beats 100% of cpp submissions
O(log(n)) solution with explanation
tags: number, bit manipulation
🔗 link
📖 description
給定兩個數字 dividend 、 divisor ,回傳 dividend/divisor ,要求不能使用乘除運算以及 mod 運算。
🧠 solution
使用 long 型別避免運算出現溢位,然後使用 bit operation 與加減法來模擬除法。
ex.
    17/3 
    1. (17 >> 2) > 3   (17 >> 2) 等價於 (17/4)
       (17 - (3 << 2) ) = 5
        那此時商就是 4 ,餘數為 5 
    2. (5 >> 1) < 3
    3. (5 >> 0) < 3    (5 >> 0)  等價於 (5/1)
       (5 - (3 << 0)) = 2
       商為 4+1 ,餘數為 2
    
    所以答案為 5 
⏳ time complexity
從第 32 個 bit 一路往下,時間複雜度為 O(log(n))
總時間複雜度 O(log(n))
📝 code
1  | class Solution {  | 
