zoukankan      html  css  js  c++  java
  • LeetCode: divideInteger

    Title:

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

    If it is overflow, return MAX_INT.

    思路就是每次以两倍增长除数,知道即将大于被除数,然后用被除数减去,在循环。

    遇到int整数问题一定要考虑到INT_MAX和INT_MIN。

    class Solution {
    public:
        int divide(int dividend, int divisor) {
            int final = 0;
            /////// overflow///////
            if (divisor == 0 || (dividend == INT_MIN && divisor == -1)){
                return INT_MAX;
            }
            int nega = 0;
            if ((dividend>0&&divisor<0) || (dividend<0&&divisor>0))
                nega = 1;
            //如果为INT_MIN则求abs为越界
            long long a = abs((long long)dividend);
            long long b = abs((long long)divisor);
            if (b > a)
                return 0;
            long long sum = 0;//后面有sum += sum防止越界
            int count = 0;
            while (a >= b)
            {
                count = 1;                //a >= b保证了最少有一个count
                sum = b;
                while (sum + sum <= a){    
                    sum += sum;
                    count += count; 
                }
                a -= sum;
                final += count;
            }
            if (nega)
                final = 0 - final;
            return final;
        }
    };
  • 相关阅读:
    Codeforces 1072
    XDOJ 1046
    BZOJ 1002
    BZOJ 1001
    BZOJ 1500/Luogu 2042
    nowcoder 211B
    BZOJ 3224
    BZOJ 1150
    POJ 2442
    二叉堆和二叉搜索树进阶
  • 原文地址:https://www.cnblogs.com/yxzfscg/p/4431165.html
Copyright © 2011-2022 走看看