1. 程式人生 > >[leetcode]29. Divide Two Integers

[leetcode]29. Divide Two Integers

Solution 1: 轉換成long 這題太變態了

第一次碰到位運算的題。

  • 首先判斷符號,>>>是右移運算子。負數的用補碼錶示,最高位是1,正數最高位是0。
boolean isNeg = (dividend^divisor)>>>31 == 1;
  • 判斷邊界條件
 if(dividend==Integer.MIN_VALUE&&divisor==-1)return Integer.MAX_VALUE;
    if (divisor == 1) return dividend;
    if (divisor == -1) return -dividend;
  • 將除數和被除數都轉換成long

  • dividend=a02的0次方+a12的一次方+…+an*2的n次方
    這裡的a0 a1… an就是我們的divisor

首先找到最大的an*2的n次方,digit儲存n

while(longdivisor<<1 <= longdividend)
    {
        longdivisor <<= 1;
        digit++;
        
    }
  • 然後不停的迭代,每一次res都加上2的n次方,直到dividend<divisor為止
while(digit>=0)
    {
        if(longdividend>=longdivisor)
        {
            res += 1<<digit;
            longdividend -= longdivisor;
        }
        longdivisor >>= 1;
        digit--;
    }
class Solution {
   public int divide(int dividend, int divisor) {
    
    boolean isNeg = (dividend^divisor)>>>31 == 1;
    int res = 0;
   
    if(dividend==Integer.MIN_VALUE&&divisor==-1)return Integer.MAX_VALUE;
    if (divisor == 1) return dividend;
    if (divisor == -1) return -dividend;
       
    
    long longdividend = Math.abs((long)dividend);
    long longdivisor = Math.abs((long)divisor);
    int digit = 0;
    while(longdivisor<<1 <= longdividend)
    {
        longdivisor <<= 1;
        digit++;
        
    }
    while(digit>=0)
    {
        if(longdividend>=longdivisor)
        {
            res += 1<<digit;
            longdividend -= longdivisor;
        }
        longdivisor >>= 1;
        digit--;
    }
    return isNeg?-res:res;
}

}