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
  • 相关阅读:
    RPM包校验和提取
    RPM包查询
    Find命令简介
    无法启动配置好的虚拟机
    文档发布至博客操作说明
    VMware Virtual Machine安装报错解决1
    python create home dircetory
    Centos7/Active Directory authentication using nss-pam-ldapd
    java try后面括号的作用
    vps上搭建jupyter notebook远程服务
  • 原文地址:https://www.cnblogs.com/yalphait/p/10338893.html
Copyright © 2011-2022 走看看