image.png
class Solution {
func divide(_ dividend: Int, _ divisor: Int) -> Int {
if dividend == 0{
return 0;
}
var isNeed = false
var dividend = dividend;
var divisor = divisor;
if dividend > 0 && divisor < 0{
isNeed = true
divisor = 0 - divisor;
}else if dividend < 0 && divisor > 0{
isNeed = true
dividend = 0 - dividend;
}else if dividend < 0 && divisor < 0{
divisor = 0 - divisor;
dividend = 0 - dividend;
}
if divisor == 1{
if isNeed {
return Int(Int32(0 - dividend));
}else{
if dividend >= 2^31{
return Int(Int32.max)
}
return Int(Int32(dividend));
}
}
var i = 0;
while divisor <= dividend {
var temp = divisor;
var cnt = 1;
while dividend >= temp{
temp = temp<<1
cnt = cnt<<1
}
i += (cnt>>1)
dividend -= (temp>>1)
}
if isNeed {
return Int(0 - i);
}else{
return Int(i);
}
}
}
网友评论