程序媛詹妮弗
终身学习
 

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.

 

题意:

不准乘除,不准膜。

 

Solution1:用加减和位运算。

乘法可以通过不断加法来获得

故,除法可以通过不断减法来获得

 

碎碎念:

数学渣对这种没有算法含量,又要大量数学sense的题,好抓狂。 

发挥文科生优势。背诵吧!!

 

code

 1 class Solution {
 2     public int divide(int dividend, int divisor) {
 3         // corner case
 4         if(dividend == 0) return 0;
 5         
 6         // 当 dividend = INT_MIN,divisor = -1时,结果会溢出
 7         if (dividend == Integer.MIN_VALUE) {
 8             if (divisor == -1) return Integer.MAX_VALUE;
 9             else if (divisor < 0)
10                 return 1 + divide( dividend - divisor, divisor);
11             else
12                 return - 1 + divide( dividend + divisor, divisor);
13         }
14         
15         if(divisor == Integer.MIN_VALUE){
16             return dividend == divisor ? 1 : 0;
17         }
18 
19         int a = dividend > 0 ? dividend : -dividend;
20         int b = divisor > 0 ? divisor : -divisor;
21 
22         int result = 0;
23         while (a >= b) {
24             int c = b;
25             for (int i = 0; a >= c;) {
26                 a -= c;
27                 result += 1 << i;
28                 if (c < Integer.MAX_VALUE / 2) { // prevent overflow
29                     ++i;
30                     c <<= 1;
31                 }
32             }
33         }
34 
35         return ((dividend^divisor) >> 31) != 0 ? (-result) : (result);
36     }
37 }

 

posted on 2019-04-15 05:56  程序媛詹妮弗  阅读(228)  评论(0编辑  收藏  举报