题目:
题解:
func divide(dividend, divisor int) int {if dividend == math.MinInt32 { // 考虑被除数为最小值的情况if divisor == 1 {return math.MinInt32}if divisor == -1 {return math.MaxInt32}}if divisor == math.MinInt32 { // 考虑除数为最小值的情况if dividend == math.MinInt32 {return 1}return 0}if dividend == 0 { // 考虑被除数为 0 的情况return 0}// 一般情况,使用二分查找// 将所有的正数取相反数,这样就只需要考虑一种情况rev := falseif dividend > 0 {dividend = -dividendrev = !rev}if divisor > 0 {divisor = -divisorrev = !rev}candidates := []int{divisor}for y := divisor; y >= dividend-y; { // 注意溢出y += ycandidates = append(candidates, y)}ans := 0for i := len(candidates) - 1; i >= 0; i-- {if candidates[i] >= dividend {ans |= 1 << idividend -= candidates[i]}}if rev {return -ans}return ans
}