Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
Not difficule, but an interesting question about the operation.
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.
My code:
class Solution:
def divide(self, dividend, divisor):
"""
:type dividend: int
:type divisor: int
:rtype: int
"""
if dividend==0:
return 0
if abs(dividend)<abs(divisor):
return 0
result=0
if (dividend>0 and divisor>0) or (dividend<0 and divisor<0):
mode=1
else:
mode=2
dividend=abs(dividend)
divisor=abs(divisor)
#ori_divisor=divisor
large_check=0
result=1
while dividend>=divisor:
divisor=divisor<<1
large_check+=1
print('large_check %d'%large_check)
for i in range(large_check):
divisor=divisor>>1
execute_label=False
if dividend>=divisor:
execute_label=True
dividend-=divisor
print('dividend %d, divisor %d'%(dividend,divisor))
if i>0:
result=result<<1
if execute_label:
result+=1
print(result)
if mode==2:
result=-result
if result>2**31-1 or result<-2**31:
return 2**31-1
return result
Solution:
https://leetcode.com/problems/divide-two-integers/