• [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 };

     

  • 相关阅读:
    构造月份选择框
    自定义验证
    设置队列中文件上的“X”号的点击事件+uploadLimit动态加1
    easyui在table单元格中添加进度条
    js里生成guid
    宽高
    获取iframe中的tree
    form表单
    position详解
    java通过jdbc连接数据库并更新数据(包括java.util.Date类型数据的更新)
  • 原文地址:https://www.cnblogs.com/chkkch/p/2789800.html
Copyright © 2020-2023  润新知