• Divide Two Integers 解答


    Question

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

    If it is overflow, return MAX_INT.

    Solution

    dividend = divisor * quotient + remainder

    而我们知道对于任何一个数可以表示为Σi * 2x  其中i为0或1。所以我们可以用加法实现乘法。

    a = a + a 等同于 a = a * 2

    因此我们可以通过对divisor乘以2,求出最大的x,然后继续求出第二大,第三大的x', x''..

    注意到可能有溢出问题,解决方法是将要计算的所有数先转为long。

     1 public class Solution {
     2     public int divide(int dividend, int divisor) {
     3         boolean negative = (dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0);
     4         long a = Math.abs((long)dividend);
     5         long b = Math.abs((long)divisor);
     6         if (a < b) {
     7             return 0;
     8         }
     9         long step, sum, result = 0;
    10         while (a >= b) {
    11             step = b;
    12             sum = 1;
    13             while (step + step <= a) {
    14                 step += step;
    15                 sum += sum;
    16             }
    17             a = a - step;
    18             result += sum;
    19         }
    20         result = negative == true ? -result : result;
    21         if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
    22             return Integer.MAX_VALUE;
    23         }
    24         return (int)result;
    25     }
    26 }
  • 相关阅读:
    go-go协程
    linux-pclint代码检测
    linux-32位-交叉编译openssl
    go-json类
    mysql-定时任务
    go-IO操作
    go-异常处理-error-panic-recover
    go-defer语句
    go-select
    go-指针
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4941501.html
Copyright © 2020-2023  润新知