Divide Two Integers
This question is very hard, just remember it:
Explaination:
思路清晰,就是二倍法。
直接用除数去一个一个加,直到被除数被超过的话,会超时。
解决办法每次将被除数增加1倍,同时将count也增加一倍,如果超过了被除数,那么用被除数减去当前和再继续本操作。因为一个很大的数经过对数处理后都能在可接受的大小内。比如Integer.MAX_VALUE 的log后也不过31.
另外这道题很恶心的一点是在边界的处理,因为我们知道最大允许的负数的绝对值比最大允许的正数要大1. 所以以后遇到这类可能越界的问题,一律用比它大的集合来装。。
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 dividend > 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE; } if (dividend == 0) { return 0; } //This is the situation where the number is out of bound; //Integer.MIN_VALUE = -2147483648 //Integer.MAX_VALUE = 2147483647 if (dividend == Integer.MIN_VALUE && divisor == -1) { return Integer.MAX_VALUE; } long a = Math.abs((long) dividend); long b = Math.abs((long) divisor); int cnt = 0; while (a >= b) { //must have equal because if it is equal, we can still deduct int shift = 0; while (a >= (b << shift)) { // equal b * 2^shift shift++; } a -= b << (shift - 1); cnt += 1 << (shift - 1); //We need the third if because if it doesn't exist, the 1 will be shift to the first bit, which will change the cnt to Integer.MIN_VALUE } int rst = (((dividend ^ divisor) >> 31) & 1) == 1? -cnt : cnt; return (int)rst; } }
posted on 2017-05-09 10:11 codingEskimo 阅读(110) 评论(0) 收藏 举报
浙公网安备 33010602011771号