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;
        }
    };
  • 相关阅读:
    AKKA学习(二) 未完
    AKKA学习(一)
    seata项目结构
    seata demo
    FESCAR
    GTS原理、架构
    Fescar使用(资料)
    高性能异步分布式事务TCC框架(资料汇总)
    TIDB学习资料
    自旋锁
  • 原文地址:https://www.cnblogs.com/yxzfscg/p/4431165.html
Copyright © 2011-2022 走看看