zoukankan      html  css  js  c++  java
  • 29. Divide Two Integers

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

    If it is overflow, return MAX_INT.

    1. nagitive

    2. overflow

    Another example : 10 / 3 = 3

    1st outer loop
    --------------
    
    1st inner loop --- tmp = 6 , count = 2
    2nd inner loop --- tmp = 12, count = 4 (exit the inner loop, result = 0 + (4 >> 1) = 2)
    
    dividend = 10 - (12 >> 1) = 10 - 6 = 4 (4 >  divisor, so here we go second outer loop)
    
    2nd outer loop
    --------------
    
    1st inner loop --- tmp = 6, count = 2 (exit the inner loop, result = 2 + (2 >> 1) = 3)
    
    dividend = 4 - (6 >> 1) = 4 - 3 = 1( divisor > 1, exit outer loop, return result)
    public class Solution {
        public int divide(int dividend, int divisor) {
            boolean isNagative = false;
            if((dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0)) isNagative = true;
            long absDivisor = Math.abs((long)divisor);
            long abdDividend = Math.abs((long)dividend);
            long res = 0;
            while(absDivisor <= abdDividend){
                long temp = absDivisor; 
                long cnt = 1;
                while(temp <= abdDividend){
                    temp <<= 1;
                    cnt <<= 1;
                }
                res += cnt >> 1;
                abdDividend -= temp>>1 ;
            }
            if(isNagative)
              res = ~res + 1;
            if (res > Integer.MAX_VALUE)
              res = Integer.MAX_VALUE;
            
             return (int) res;
        }
    }
     
  • 相关阅读:
    查看git submodule更改
    /var/lib/docker空间占用过大迁移
    docker -修改容器
    docker重命名镜像repository和tag
    方法的重写、重载。
    方法的声明与使用。
    二维数组。
    标准输入输出流概述和输出语句。
    冒泡排序法。
    IO流,对象操作流优化。
  • 原文地址:https://www.cnblogs.com/joannacode/p/6116312.html
Copyright © 2011-2022 走看看