码迷,mamicode.com
首页 > 其他好文 > 详细

[Twitter] Divide Without / Or %

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

标签:leetcode   twitter   

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 %

标签:leetcode   twitter   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!