Given two integers dividend and divisor, divide two integers without
using multiplication, division and mod operator.Return the quotient after dividing dividend by divisor.ide
The integer division should truncate toward zero.this
Example 1:設計
Input: dividend = 10, divisor = 3 Output: 3 Example 2:code
Input: dividend = 7, divisor = -3 Output: -2 Note:ip
Both dividend and divisor will be 32-bit signed integers. The divisor
will never be 0. Assume we are dealing with an environment which could
only store integers within the 32-bit signed integer range: [−231,
231 − 1]. For the purpose of this problem, assume that your function
returns 231 − 1 when the division result overflows.
兩個點須要注意
1.這樣設計到大數運算的又不能使用乘除法的確定要使用移位符
2.注意溢出的判斷,這道題就適合更改輸入條件,但要注意修改了原始輸入值,是否影響後面的判斷it
public int divide(int dividend, int divisor) { int ret=0; boolean up=true; if((dividend>0 && divisor<0)||(dividend<0 && divisor>0)) up=false; if(divisor==Integer.MIN_VALUE){ if(dividend==Integer.MIN_VALUE) return 1; else return 0; } if(dividend==Integer.MIN_VALUE) { if(divisor==-1) return Integer.MAX_VALUE; else{ ret++; dividend+=Math.abs(divisor); } } divisor=Math.abs(divisor); dividend=Math.abs(dividend); while(dividend>=divisor){ int count=1; int power=divisor; while(dividend>>2>=power){ count=count<<1; power=power<<1; } ret+=count; dividend-=power; } return up?ret:-ret; }