Divide Two Integers:Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
题意:实现整数的除法,不能使用/运算符。
思路:参考http://blog.csdn.net/linhuanmars/article/details/20024907?utm_source=tuicool&utm_medium=referral
代码:
public class Solution { public int divide(int dividend, int divisor) { if(dividend == 0) { return 0;} boolean isNeg = (dividend^divisor)>>>31 == 1; int res = 0; if(dividend == Integer.MIN_VALUE){ dividend += Math.abs(divisor); if(divisor==-1){ return Integer.MAX_VALUE; } res++; } if(divisor==Integer.MIN_VALUE){ return res; } dividend = Math.abs(dividend); divisor = Math.abs(divisor); int digit = 0; while(divisor<= (dividend>>1)){ divisor<<=1; digit++; } while(digit>=0){ if(dividend >= divisor){ res += 1<<digit; dividend -= divisor; } divisor >>=1; digit--; } return isNeg ? -res:res; } }