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

Divide Two Integers

时间:2014-05-15 14:40:50      阅读:285      评论:0      收藏:0      [点我收藏+]

标签:java   pat   

Divide two integers without using multiplication, division and mod operator.


public class Solution {
  public int divide(int dividend, int divisor) {
    int sign = 1;
    if (dividend < 0) {
      sign *= -1;
    }
    if (divisor < 0) {
      sign *= -1;
    }

    long big = Math.abs((long) dividend);
    long small = Math.abs((long) divisor);
    long temp = small;
    long midres = 1;
    while (temp < big) {
      temp <<= 1;
      midres <<= 1;
    }

    int ret = 0;
    while (temp >= small) {
      while (big >= temp) {
        big -= temp;
        ret += midres;
      }
      temp >>= 1;
      midres >>= 1;
    }
    return ret * sign;
  }
}


Divide Two Integers,布布扣,bubuko.com

Divide Two Integers

标签:java   pat   

原文地址:http://blog.csdn.net/jason_wang1989/article/details/25708355

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