zoukankan      html  css  js  c++  java
  • [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.

    题目

    不准乘除,不准膜。

    思路

    那剩下的还能用加减、位运算

    代码

     1 // Divide Two Integers
     2 // 时间复杂度O(logn),空间复杂度O(1)
     3 public class Solution {
     4     public int divide(int dividend, int divisor) {
     5         if(dividend == 0) return 0;
     6         if (divisor == 0) return Integer.MAX_VALUE;
     7 
     8         // 当 dividend = INT_MIN,divisor = -1时,结果会溢出
     9         if (dividend == Integer.MIN_VALUE) {
    10             if (divisor == -1) return Integer.MAX_VALUE;
    11             else if (divisor < 0)
    12                 return 1 + divide(dividend - divisor, divisor);
    13             else
    14                 return - 1 + divide((dividend + divisor), divisor);
    15         }
    16         if(divisor == Integer.MIN_VALUE){
    17             return dividend == divisor ? 1 : 0;
    18         }
    19 
    20         int a = dividend > 0 ? dividend : -dividend;
    21         int b = divisor > 0 ? divisor : -divisor;
    22 
    23         int result = 0;
    24         while (a >= b) {
    25             int c = b;
    26             for (int i = 0; a >= c;) {
    27                 a -= c;
    28                 result += 1 << i;
    29                 if (c < Integer.MAX_VALUE / 2) { // prevent overflow
    30                     ++i;
    31                     c <<= 1;
    32                 }
    33             }
    34         }
    35 
    36         return ((dividend^divisor) >> 31) != 0 ? (-result) : (result);
    37     }
    38 }
  • 相关阅读:
    2021hdu多校第二场补题
    ORACLE数据库之SQL语言基础
    EXCEL应用
    element-ui闭坑
    题解 CF1559E 【Mocha and Stars】
    题解 CF1530D 【Secret Santa】
    题解 CF1209E2 【Rotate Columns (hard version)】
    题解 CF761E 【Dasha and Puzzle】
    题解 UVA437 【巴比伦塔 The Tower of Babylon】
    题解 P6100 【[USACO19FEB]Painting the Barn G】
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9810665.html
Copyright © 2011-2022 走看看