首页 > 其他 > 详细

[Twitter] Divide Without / Or %

时间:2015-01-16 08:44:01      阅读:283      评论:0      收藏:0      [点我收藏+]

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 %

原文:http://7371901.blog.51cto.com/7361901/1604612

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!