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

    Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.

    Return the quotient after dividing dividend by divisor.

    The integer division should truncate toward zero.

    Example 1:

    Input: dividend = 10, divisor = 3
    Output: 3

    Example 2:

    Input: dividend = 7, divisor = -3
    Output: -2

    Note:

    • Both dividend and divisor will be 32-bit signed integers.
    • The divisor will never be 0.
    • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.

    题意

    不使用mod或除法来实现除法运算

    题解

    一开始使用暴力,非常慢,然后用了二分,快了

     1 class Solution {
     2 public:
     3     int divide(long long dividend, long long divisor) {
     4         long long s = 0, e = (long long)INT_MAX+1;
     5         long long res = dividend ^ divisor;
     6         if (dividend < 0)
     7             dividend = -dividend;
     8         if (divisor < 0)
     9             divisor = -divisor;
    10         while (s+1<e) {
    11             long long mid = (s + e) / 2;
    12             if (mid*divisor <= dividend)
    13                 s = mid;
    14             else
    15                 e = mid-1;
    16         }
    17         if (e*divisor <= dividend)s = e;
    18         if (res < 0)s = -s;
    19         if (s > INT_MAX)s = INT_MAX;
    20         if (s < INT_MIN)s = INT_MIN;
    21         return s;
    22     }
    23 };
    View Code
  • 相关阅读:
    SQL审核平台
    Redis单线程为什么快简单理解
    性能测试关注指标
    nmon
    pycharm安装教程
    MAVEN中央仓库地址大全
    MAVEN概念、安装与配置、配置文件
    linux在线模拟地址
    HTTP学习链接、书籍
    Java启动exe
  • 原文地址:https://www.cnblogs.com/yalphait/p/10338893.html
Copyright © 2011-2022 走看看