• Leetcode: 29. Divide Two Integers


    Description

    Divide two integers without using multiplication, division and mod operator.

    If it is overflow, return MAX_INT.

    思路

    • 不允许用乘法,除法和取模
    • 除法可以使用减法实现
    • 如果每一次单个单个减的话,太慢。所以用移位来增加每一次减的数
    • 比如19/2,首先 2 << 3 = 16, res += 1 << 3 = 8;
    • 然后 19 - 16 = 3; 3 / 2 , res += 1 << 0 = 9;
    • 最后 3 - 2 = 1, 1/2 = 0, 所以 res = 9
    • 主要是边界值的考虑
      • -2147483648 / -1 = 2147483647
      • -2147483648 / -1 = -2147483648
      • ...
    • 代码打了太多补丁了。。

    代码

    class Solution {
    public:
        int divide(int dividend, int divisor) {
            
            if(divisor == INT_MIN && dividend == INT_MIN) return 1;
            if(divisor == INT_MIN || dividend == 0) return 0; 
            if(divisor == 0) return INT_MAX;
            
            bool isNegative = false, isINT_MIN = false;
            if(dividend < 0){
                isNegative = !isNegative;
                if(dividend == isINT_MIN)
                    isINT_MIN = true;
                else dividend = -dividend;
            }
            
            if(divisor < 0){
                isNegative = !isNegative;
                divisor = -divisor;
            }
            
            int res = 0, tmp = 0, count = 0;
            while(dividend >= divisor || dividend == INT_MIN){
                tmp = divisor;
                count = 0;
                while(1){
                    int next = tmp << 1;
                    if(tmp > next) break;
                    
                    if((dividend > next) || (dividend == INT_MIN && INT_MAX > next)){
                        tmp = next;
                        count++;
                    }
                    else break;
                }
                
                if(dividend >= tmp || dividend == INT_MIN)
                    res += 1 << count;
               
                if(isINT_MIN){
                    dividend += tmp;
                    dividend = -dividend;
                    isINT_MIN = false;
                }
                else
                    dividend -= tmp;
            }
            
            if(res < 0)
                return isNegative ? res : INT_MAX;
            else 
                return isNegative ? -res :  res;
        }
    };
    
  • 相关阅读:
    JUnit4的使用
    Android中使用JUnit4测试发生fatal error
    计算器的M+是什么意思
    初识Ildasm.exe——IL反编译的实用工具
    jsp下载
    jsp文件上传
    java.sql.SQLException: Io 异常:
    在PowerDesigner中创建物理模型时DBMS选项为空
    oracle10g还原被drop的表
    oracle创建用户
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6825099.html
Copyright © 2020-2023  润新知