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
  • 相关阅读:
    一个想法开发与业务,我们互相依赖
    vs2005中文包,和sqlserver2005中文开发版
    C中的指针
    建立一个新的web Site
    Visual Studio 2005 中的新增安全性功能
    htm和html的区别
    完美实现导航滑动功能
    如何避免AJAX的缓存问题
    两个常用的稳定的远端CDN jquery
    推荐一个CSS排错的网址
  • 原文地址:https://www.cnblogs.com/yalphait/p/10338893.html
Copyright © 2011-2022 走看看