代码改变世界
[登录 · 注册]
  • Divide Two Integers
  • 参考:http://www.cnblogs.com/springfor/p/3871008.html

    Divide two integers without using multiplication, division and mod operator.

    If it is overflow, return MAX_INT.

    这道看了网上的很多都是通过移位来做的,硬是没看懂

    看了一下这个锅锅的,终于懂了

     1 public class Solution {
     2     public int divide(int dividend, int divisor) {
     3         if(0 == dividend || 0 == divisor)
     4             return 0;
     5         boolean isNeg = ((dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0)) ? true : false;
     6         long dividen_long = Math.abs((long)dividend);
     7         long divisor_long = Math.abs((long)divisor);
     8         if(divisor_long > dividen_long)
     9             return 0;
    10         
    11         long sum = 0;
    12         long pow = 0;
    13         long result = 0;
    14         
    15         while(divisor_long <= dividen_long){
    16             sum = divisor_long;
    17             pow = 1;
    18             while(sum + sum <= dividen_long){
    19                 sum += sum;
    20                 pow += pow;
    21             }//while
    22             dividen_long -= sum;
    23             result += pow;
    24         }//while
    25         
    26         result = isNeg ?  -result : result;
    27         if(result > Integer.MAX_VALUE || result < Integer.MIN_VALUE)
    28             return Integer.MAX_VALUE;
    29         
    30         return (int)result;
    31     }
    32 }
  • 【推广】 阿里云小站-上云优惠聚集地(新老客户同享)更有每天限时秒杀!
    【推广】 云服务器低至0.95折 1核2G ECS云服务器8.1元/月
    【推广】 阿里云老用户升级四重礼遇享6.5折限时折扣!
  • 原文:https://www.cnblogs.com/luckygxf/p/4228951.html
Copyright 2008-2020 晋ICP备12007731号-1