leetcode_29_Divide Two Integers

版权所有,欢迎转载,转载请注明出处,谢谢

Divide Two Integers

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

If it is overflow, return MAX_INT.

用减法做:超时。例如:(dividend, divisor) = (2147483647, 1)

方法一:利用二分法。

假设:要求的解在[a, b]中。(而本题中,解存在的范围为[0, dividend])

divisor * (a + b) / 2 > dividend => 解在[a, (a + b) / 2 - 1]中;

divisor * (a + b) / 2 == dividend => 解为(a + b) / 2;

divisor * (a + b) / 2 < dividend => 解在[(a + b) / 2 + 1, b]中或者解就是(a + b) / 2。

(因为不一定能够刚刚好整除,例如(dividend, divisor) = (5, 2),解为2)

求取(a + b) / 2可以用移位操作;

求取divisor * (a + b)/2 可以用二分加移位。

因此整个复杂度为O(logNlogN)。

P.S. 需要注意符号和数据越界。

//vs2012测试代码
#include<iostream>

using namespace std;

class Solution {
private:
	long long multiplication(long long mid2, long long divisor2)
	{
		if (mid2 == 0) {
			return 0;
		}
		long long temp = multiplication(mid2 >> 1, divisor2) << 1;
		if ((mid2 & 1) != 0) {
			temp += divisor2;
		}
		return temp;
	}
public:
    int divide(int dividend, int divisor)
	{
		int flag=1;
		long long ans=0;
        if(divisor == 0)
			return INT_MAX;
		if(dividend == 0)
			return 0;
		if( (dividend<0 && divisor>0) || (dividend>0 && divisor<0) )
		{
			flag=-1;
		}

		long long dividend1 = abs((long long)dividend);
		long long divisor1 = abs((long long)divisor);
		long long left=0, right=dividend1, mid=-1;
		long long temp=0;
		while(left<=right)
		{
			mid = left + ((right-left)>>1);
			temp = multiplication( mid,divisor1);
			if(temp == dividend1)
			{
				ans = mid;
				break;
			}
			else if(temp>dividend1)
				right = mid - 1;
			else if(temp<dividend1)
			{
				ans = mid;
				left = mid + 1;
			}
		}
		ans = flag>0? ans : -ans;
		//着重考虑边界条件,容易忽略
		if( ans > INT_MAX || ans < INT_MIN)
			return INT_MAX;
		return ans;
    }
};

int main()
{
	int dividend,divisor;
	cin>>dividend;
	cin>>divisor;
	Solution lin;
	cout<<lin.divide( dividend,divisor )<<endl;
}
//方法一:自测Accepted
class Solution {
private:
	long long multiplication(long long mid2, long long divisor2)
	{
		if (mid2 == 0) {
			return 0;
		}
		long long temp = multiplication(mid2 >> 1, divisor2) << 1;
		if ((mid2 & 1) != 0) {
			temp += divisor2;
		}
		return temp;
	}
public:
    int divide(int dividend, int divisor)
	{
		int flag=1;
		long long ans=0;
        if(divisor == 0)
			return INT_MAX;
		if(dividend == 0)
			return 0;
		if( (dividend<0 && divisor>0) || (dividend>0 && divisor<0) )
		{
			flag=-1;
		}

		long long dividend1 = abs((long long)dividend);
		long long divisor1 = abs((long long)divisor);
		long long left=0, right=dividend1, mid=-1;
		long long temp=0;
		while(left<=right)
		{
			mid = left + ((right-left)>>1);
			temp = multiplication( mid,divisor1);
			if(temp == dividend1)
			{
				ans = mid;
				break;
			}
			else if(temp>dividend1)
				right = mid - 1;
			else if(temp<dividend1)
			{
				ans = mid;
				left = mid + 1;
			}
		}
		ans = flag>0? ans : -ans;
		//着重考虑边界条件,容易忽略
		if( ans > INT_MAX || ans < INT_MIN)
			return INT_MAX;
		return ans;
    }
};
//方法:超时
class Solution {
public:
    int divide(int dividend, int divisor)
	{
        if(divisor == 0)
			return INT_MAX;
		else if(dividend == 0)
			return 0;
		else if(dividend>0 && divisor>0)
		{
			int count=0;
			while(1)
			{
				if(dividend < divisor)
					return count;
				else
				{
					dividend = dividend - divisor ;
					count++;
				}
			}
		}
		else if(dividend<0 && divisor<0)
		{
			dividend = -dividend;
			divisor = -divisor;
			int count=0;
			while(1)
			{
				if(dividend < divisor)
					return count;
				else
				{
					dividend = dividend - divisor ;
					count++;
				}
			}
		}
		else if(dividend>0 && divisor<0)
		{
			divisor = -divisor;
			int count=0;
			while(1)
			{
				if(dividend < divisor)
					return count;
				else
				{
					dividend = dividend - divisor ;
					count--;
				}
			}
		}
		else if(dividend<0 && divisor>0)
		{
			dividend = -dividend;
			int count=0;
			while(1)
			{
				if(dividend < divisor)
					return count;
				else
				{
					dividend = dividend - divisor ;
					count--;
				}
			}
		}
    }
};
时间: 2024-10-14 17:09:30

leetcode_29_Divide Two Integers的相关文章

TypeError: string indices must be integers, not str

1. TypeError: string indices must be integers, not str 字符串类型取第index个字符的时候,应该传入int而不是str.如 view source print? 1 a='abcdef' 2 print a[0] 3 #而不是 print a['0'] 更常见的情况是把一个string当成了字典在使用 :should_be_dict_but_string['id'] .这样的错误

[TypeScript] Create random integers in a given range

Learn how to create random integers using JavaScript / TypeScript. /** * Returns a random int between * @param start inclusive * @param before exclusive */ export function randomInt(start: number, before: number) { return start + Math.floor(Math.rand

HDU 1796How many integers can you find(容斥原理)

How many integers can you find Time Limit:5000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u Submit Status Practice HDU 1796 Description Now you get a number N, and a M-integers set, you should find out how many integers which are smal

29. Divide Two Integers

Divide two integers without using multiplication, division and mod operator. If it is overflow, return MAX_INT. (1) log int divide(int dividend, int divisor) { if(dividend == 0) return 0; if(divisor == 0) return INT_MAX; double t1 = log(fabs(dividend

E - A Simple Problem with Integers

#include <iostream> #include <stdio.h> #include <string.h> #include <stdlib.h> using namespace std; #define N 100002 struct node { int l,r; long long lz,w; }q[4*N]; void pushup(int rt) { q[rt].w=q[rt*2].w+q[rt*2+1].w; } void pushdo

371. Sum of Two Integers

Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Example: Given a = 1 and b = 2, return 3. Credits: Special thanks to @fujiaozhu for adding this problem and creating all test cases. 这道题让我们实现两数相加,但是不能用加号或

POJ 3468 A Simple Problem with Integers

链接:http://poj.org/problem?id=3468 A Simple Problem with Integers Time Limit: 5000MS Memory Limit: 131072K Total Submissions: 77302 Accepted: 23788 Case Time Limit: 2000MS Description You have N integers, A1, A2, ... , AN. You need to deal with two ki

poj 3468 A Simple Problem with Integers(线段树+区间更新+区间求和)

题目链接:id=3468http://">http://poj.org/problem? id=3468 A Simple Problem with Integers Time Limit: 5000MS   Memory Limit: 131072K Total Submissions: 83959   Accepted: 25989 Case Time Limit: 2000MS Description You have N integers, A1, A2, ... , AN. Yo

A Simple Problem with Integers

Time Limit: 5000MS   Memory Limit: 131072K Total Submissions: 99895   Accepted: 31162 Case Time Limit: 2000MS Description You have N integers, A1, A2, ... , AN. You need to deal with two kinds of operations. One type of operation is to add some given