LeetCode Divide Two Integers(***)
2014-06-17 15:38
288 查看
Divide two integers without using multiplication, division and mod operator.
用移位操作实现乘以2、除以2,对除数进行翻倍的扩大操作,记录翻倍次数,然后把被除数减去最大的除数,依次进行,直到被除数小于除数,得到结果。
这里注意取绝对值的时候,最小负数的处理。
用移位操作实现乘以2、除以2,对除数进行翻倍的扩大操作,记录翻倍次数,然后把被除数减去最大的除数,依次进行,直到被除数小于除数,得到结果。
这里注意取绝对值的时候,最小负数的处理。
class Solution { public: const int MAXVALUE = ~(1<<31); const int MINVALUE = -(~(1<<31))-1; int divide(int dividend, int divisor) { int res=0; if(divisor==0)return MAXVALUE; //当除数为0时,return 最大正整数 if(dividend==MINVALUE){ res=1; dividend+=abs(divisor); //当被除数为最小负数时,+个除数然后被除数取绝对值 } if(divisor==MINVALUE)return res;//当除数为最小负数时,要么为0,要么为1,决定于被除数是否也为最小负数 int isNeg = ((dividend^divisor)>>31==0)?false:true; dividend = abs(dividend); divisor = abs(divisor); int digit=0; while(divisor<=(dividend>>1)){ //记录最大的翻倍次数 digit++; divisor<<=1; } while(digit>=0){ //翻倍次数递减,如果dividend>=divisor时,记录res并把dividend=dividend-divisor if(divisor<=dividend){ res+=1<<digit; dividend-=divisor; } divisor>>=1; digit--; } return isNeg==true?-res:res; } };
相关文章推荐
- leetcode - 29.Divide Two Integers
- leetcode第28题--Divide Two Integers
- leetcode--29. Divide Two Integers
- Leetcode: Divide Two Integers
- Leetcode---Divide Two Integers
- LeetCode:Divide Two Integers
- [LeetCode] Divide Two Integers
- 【LeetCode】P029_DivideTwoIntegers
- LeetCode - 29. Divide Two Integers
- LeetCode-Divide Two Integers
- leetcode - Divide Two Integers
- LeetCode Divide Two Integers
- [leetcode 29]divide two integers
- LeetCode 29. Divide Two Integers
- LeetCode(29)Divide Two Integers
- [LeetCode]29. Divide Two Integers
- Leetcode-Divide Two Integers
- LeetCode-029 Divide Two Integers
- 【LeetCode】29. Divide Two Integers
- 【Leetcode】Divide Two Integers