首页 > 代码库 > [Twitter] Divide Without / Or %
[Twitter] Divide Without / Or %
Question:
Implement Integer division without using / or %.
http://www.glassdoor.com/Interview/Implement-integer-division-without-using-or-Questions-about-running-time-Can-you-do-it-faster-QTN_250205.htm
// A binary question // return a / b. public int divide(int a, int b) { if (b == 0) return Integer.MAX_VALUE; if (a == 0) return 0; boolean neg = (a < 0 && b > 0) || (a > 0 && b < 0); a = Math.abs(a); b = Math.abs(b); long low = 1L; long high = a; while (low < high) { long mid = low + ((high - low) >> 1); long r = mid * b; if (r == a) return neg ? -mid : mid; else if (r > a) high = mid - 1; else low = mid + 1; } return neg ? -low : low; }
[Twitter] Divide Without / Or %
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。