zoukankan      html  css  js  c++  java
  • 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;
        }
    };
    
  • 相关阅读:
    Foundations of Machine Learning: The PAC Learning Framework(2)
    Foundations of Machine Learning: The PAC Learning Framework(1)
    图形渲染流水线
    如何用python的装饰器定义一个像C++一样的强类型函数
    Python 装饰器学习心得
    PAT 1087 All Roads Lead to Rome
    PAT 1086 Tree Traversals Again
    PAT 1085 Perfect Sequence
    PAT 1084 Broken Keyboard
    LeetCode: Sort Colors
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6825099.html
Copyright © 2011-2022 走看看