标签:
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return 2147483647
public class Solution { /** * @param dividend the dividend * @param divisor the divisor * @return the result */ public int divide(int dividend, int divisor) { // Write your code here if(divisor == 0) return 2147483647; if(dividend == 0) return 0; if(divisor == 1) return dividend; if (dividend == Integer.MIN_VALUE && divisor == -1) { return Integer.MAX_VALUE; } boolean neg = (dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0); long num = Math.abs((long) dividend); long den = Math.abs((long) divisor); long result = 0; while(num >= den){ int shift = 0; while(num >= (den << shift)) shift++; num -= den<<(shift - 1); result += 1 << (shift - 1); } if(neg){ if(result > Math.abs((long) Integer.MIN_VALUE)) return 2147483647; else return (int) (-result); } else{ if(result > (long) Integer.MAX_VALUE) return 2147483647; else return (int) result; } } }
lintcode-medium-Divide Two Integers
标签:
原文地址:http://www.cnblogs.com/goblinengineer/p/5297507.html