LeetCode 刷题日记 29

不使用乘除模运算,完成对两个数的相除运算

规定 : 结果溢出返回 int 型最大值

考虑溢出情况  Integer.MIN_VALUE /(-1)  = - Integer.MIN_VALUE  = Integer.MAX_VALUE + 1  ,此时显然超出了正数最大值,溢出,则返回Integer.MAX_VALUE

其余除法不导致溢出

考虑 100 / 3

翻译成减法就是100 减多少个3  才能差比3 小,每次只减一个3。测试如果用例使用:Integer.MAX_VALUE和1,则时间超时,因为每次只减一个数

选择 一次减一个1 ,第二次减两个1,第三次减4个1

设dividend 和 divisor 已转为正数long型:

int ans = 0; // 保存答案;

int sum = 0;

while(dividend >= divisor){

    sum = divisor;  // 每次循环的和

    int cnt = 1; // 每次循环统计这一次含有多少divisor

    while(sum + sum <= dividend){ 

           sum += sum;  // 1+1,2 + 2, 4+ 4

           cnt += cnt;

    }

    ans = ans + cnt; //ans 存储量cnt 个 divisor, 之后累加

    dividend -= sum; // 剩余没处理的dividend

}

return ans;

猜你喜欢

转载自www.cnblogs.com/tiansiyuan-program/p/9771516.html