zoukankan      html  css  js  c++  java
  • [LeetCode] Divide Two Integers

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

     1 class Solution {
     2 private:
     3     long long f[100];
     4 public:
     5     int bsearch(long long a[], int left, int right, long long key)
     6     {
     7         if (left > right)
     8             return -1;
     9             
    10         int mid = left + (right - left) / 2;
    11         if (a[mid] == key)
    12             return mid;
    13         else if (a[mid] < key)
    14         {
    15             int pos = bsearch(a, mid + 1, right, key);
    16             return pos == -1 ? mid : pos;
    17         }
    18         else
    19         {
    20             return bsearch(a, left, mid - 1, key);
    21         }
    22     }
    23     
    24     int divide(int dividend, int divisor) {
    25         // Start typing your C/C++ solution below
    26         // DO NOT write int main() function
    27         int sign = dividend < 0 ? -1 : 1;
    28         if (divisor < 0)
    29             sign *= -1;
    30         
    31         long long div = dividend;
    32         div = abs(div);
    33         long long divisorL = divisor;
    34         divisorL = abs(divisorL);
    35         f[0] = divisorL;
    36         int size = 1;
    37         while(true)
    38         {
    39             if (f[size-1] >= div)
    40                 break;
    41             f[size] = f[size-1] + f[size-1];
    42             size++;
    43         }
    44         
    45         int num = 0;
    46         long long sum = 0;
    47         while(div > 0)
    48         {
    49             int pos = bsearch(f, 0, size - 1, div);
    50             if (pos == -1)
    51                 break;
    52             div -= f[pos];
    53             num += (1 << pos);
    54         }
    55                 
    56         return num * sign;
    57     }
    58 };

     

  • 相关阅读:
    工厂模式
    不错公众号
    linux 下的 正则表达式(awk,sed,awk)学习
    CentOS 7 中安装 bcc-tools
    docker
    Python爬去知乎上问题下所有图片
    过滤重复数据取一条
    阿里云80端口被系统占用
    过滤重复项取时间最近的数据
    Layui的几个问题记录一下
  • 原文地址:https://www.cnblogs.com/chkkch/p/2789800.html
Copyright © 2011-2022 走看看