C语言 | Leetcode C语言题解之第29题两数相除

题目:

题解:

cpp 复制代码
int divide(int dividend, int divisor){
    int cnt = 0;
    int sign = 1;
    if ((dividend ^ divisor) < 0) { // 两数任意一个为负数
        sign = -1;
    }
    if (divisor == INT_MIN) { // 除数边界值特殊处理
        if (dividend == INT_MIN) {
            return 1;
        } else {
            return 0;
        }
    }
    if (dividend == INT_MIN) { // 被除数边界值特殊处理
        if (divisor == -1) {
            return INT_MAX;
        } else if (divisor == 1) {
            return INT_MIN;
        }
        dividend += abs(divisor); // 先执行一次加操作,避免abs转换溢出
        cnt++;
    } 
    int a = abs(dividend);
    int b = abs(divisor);
    while (a >= b) {
        int c = 1;
        int s = b;
        // 需指数级快速逼近,以避免执行超时
        while (s < (a >> 1)) { // 逼近至一半,同时避免溢出
            s += s;
            c += c;
        }
        cnt += c;
        a -= s;
    }
    return (sign == -1) ? -cnt : cnt;
}
相关推荐
祈安_3 小时前
C语言内存函数
c语言·后端
norlan_jame2 天前
C-PHY与D-PHY差异
c语言·开发语言
琢磨先生David2 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
czy87874752 天前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
m0_531237172 天前
C语言-数组练习进阶
c语言·开发语言·算法
超级大福宝2 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
Charlie_lll2 天前
力扣解题-88. 合并两个有序数组
后端·算法·leetcode
菜鸡儿齐2 天前
leetcode-最小栈
java·算法·leetcode
Frostnova丶2 天前
LeetCode 1356. 根据数字二进制下1的数目排序
数据结构·算法·leetcode
Z9fish2 天前
sse哈工大C语言编程练习23
c语言·数据结构·算法