public class Solution { public int divide(int dividend, int divisor) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if(dividend == 0) return 0; if(divisor == 1) return dividend; boolean negative = false; if(dividend < 0 && divisor > 0) negative = true; if(dividend > 0 && divisor < 0) negative = true; long[] mydivisor = new long[32]; long ldivisor = (long)Math.abs((long)divisor); long ldividend = (long)Math.abs((long)dividend); int i = 0; while(i < 32) { if(ldividend >= ldivisor) { mydivisor[i] = ldivisor; ldivisor <<= 1; } else { i--; break; } i++; } int result = 0; while(i>=0) { if(ldividend - mydivisor[i] >= 0) { ldividend -= mydivisor[i]; result += (1<<i); } else { i--; } } if(negative) return ~result + 1; else return result; } }
两个数的除法,但是不允许用乘、除、取余符号。
[解题思路]
如果可以用乘的话,二分搜索倒是不错的解法。
否则,只能寄希望于位符操作了。
基本思想就是把除数向左移位(×2)然后与被除数比较,直到发现仅次于被除数的那个值,减去该值后继续。也可以用递归做,这里图省事,就是一个循环了事。
ref:http://fisherlei.blogspot.com/2012/12/leetcode-divide-two-integers.html