zoukankan      html  css  js  c++  java
  • LeetCode Divide Two Integers

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

    If it is overflow, return MAX_INT.

    举个例子比较容易理解,74 / 5, 这里 5*2=10 < 10*2=20 < 20*2=40 <  40*2=80,可以得到 5*8<74;然后剩下34,使用这一方法继续计算5*4=20 < 34,剩余14, 5*2<14,余下4舍去。故结果为8+4+2=14。

    class Solution {
    public:
        int divide(int dividend, int divisor) 
    {
    	int ret = 0;
    	int count = 0;
    	
    	long long fDivisor = divisor;
    	long long fDividend = dividend;
    	long long a = abs(fDividend);
    	long long b = abs(fDivisor);
    	long long sum = 0;
    	int final = 0;
    	bool flag = false;
    	if(!fDivisor || (fDividend==INT_MIN&&fDivisor==(-1))) return INT_MAX;
    	if(fDivisor ==0 || fDividend ==0)
    		return 0;
    
    	if(a  < b)
    	{
    		return 0;
    	}
    
    	while(a >= b)
    	{
    		int count = 1;
    		sum = b;
    		while(sum + sum < a)
    		{
    			sum += sum;
    			count += count;
    		}
    		a -= sum;
    		final += count;
    	}
    
    	if(fDividend * fDivisor < 0)
    	{
    	 final = (-1)*final;
    	}
    	return final;
    }
    };
    
  • 相关阅读:
    Mark
    linux重启mysql无法启动
    网络流量监测IP雷达 4.0
    BBR拥塞控制算法
    弱口令
    SSH加固
    Openstack 部署
    Integrate Neutron and OVN
    Build OpenVSwitch and OVN
    OVN 简单组网脚本
  • 原文地址:https://www.cnblogs.com/bestwangjie/p/5297789.html
Copyright © 2011-2022 走看看