LCR001-两数相除

求解代码

java 复制代码
    //定义移位边界,防止左移溢出
    private static final int BOUND = Integer.MIN_VALUE>>1;

    //被除数是最小负数,除数是-1,返回最大正数
    public int divide(int a,int b){
        if(a==Integer.MIN_VALUE&&b==-1){
            return Integer.MAX_VALUE;
        }

        if(a==0||b==1){
            return a;
        }else if(b == -1){
            return -a;
        }

        int negative = 2;
        // 统一转为负数计算,避免MIN_VALUE取反溢出
        if(a>0){
            negative--;
            a=-a;
        }

        //仅处理a、b均为负数的情况,返回正的商
        if(b>0){
            negative--;
            b=-b;
        }

        int ans = helpDivide(a,b);
        return negative == 1 ? -ans : ans;
    }

    private int helpDivide(int a,int b){
        // 被除数绝对值 == 除数绝对值,商为1
       if(a==b){
        return 1;
       } 
       int res = 0;
       int shift = getMaxShift(a,b);
       while(a<=b){
        while (a>(b<<shift)) {
            shift--;
        }
        a-=(b<<shift);// 减去 b×2^shift
        res+=(1<<shift);// 商累加 2^shift
       }
       return res;
    }

    // 获取除数b的最大有效移位次数
    private int getMaxShift(int a,int b){
        int shift = 0;
        int tmp = b;

        while(tmp>a && tmp>=BOUND){
            tmp<<=1;
            shift++;
        }
        return shift;
    }

小贴士

必须以除数 为起点左移(倍增),而非被除数

Integer.MIN_VALUE = -2^31 取反会溢出。

两个负数相比较时,a更小表示绝对值更大。

相关推荐
PPPPickup4 分钟前
基础知识差缺补漏-面试版持续更新
java·开发语言
深入云栈11 分钟前
Nacos 2.x 源码深度解析 (二):通信协议迭代 —— HTTP长轮询到gRPC演进
java
兔兔兔兔128 分钟前
记录C++ 3
开发语言·c++
andongni20329 分钟前
SpringBoot 入门实验报告
java·spring boot·后端
黄鸭部落格ShiYuYuanFang30 分钟前
【分享】软考每日一练与解析-计组 8/12
java·开发语言
m0_6174939432 分钟前
Python 使用 cryptography 实现数据加密与解密
开发语言·python
大白同学42136 分钟前
初始Qt——了解Qt背景
开发语言·qt
XWalnut1 小时前
LeetCode刷题 day37
java·数据结构·算法·leetcode
万山寒1 小时前
python依赖包导出离线安装到没有外网的服务器
服务器·开发语言·python
huaweichenai1 小时前
使用maven搭建sprint-boot
java·maven·sprint