zoukankan      html  css  js  c++  java
  • LeetCode

    题目:

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

    If it is overflow, return MAX_INT.

    思路:

    吐槽这种题目,这就像你明明可以买到过年回家的直达票,有票且一键解决,却去买分段票,路途不耽误时间吗?而且买分段票时中间容易出差错(bugs),最终可能回不了家(运行结果错误)。

    package manipulation;
    
    public class DivideTwoIntegers {
    
        public int divide(int dividend, int divisor) {
            if ((dividend == Integer.MIN_VALUE && divisor == -1) || divisor == 0) return Integer.MAX_VALUE;
            if (divisor == 1) return dividend;
            if (divisor == -1) return -dividend;
            
            long a = Math.abs((long)dividend);
            long b = Math.abs((long)divisor);
            
            long base = b;
            int i = 0;
            long[] nums = new long[32];
            nums[0] = b;
            while (nums[i] <= a && nums[i] > 0) {
                nums[i+1] = base << (i+1);
                ++i;
            }
            --i;
            
            int cnt = 0;
            while (a > 0 && i >= 0) {
                while (a - nums[i] >= 0) {
                    a -= nums[i];
                    cnt += (1 << i);
                }
                --i;
            }
            
            return ((dividend ^ divisor) >> 31) == 0 ? cnt : -cnt;
        }
        
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            DivideTwoIntegers d = new DivideTwoIntegers();
            System.out.println(d.divide(-2147483648, 2));
        }
    
    }
  • 相关阅读:
    I/O FileInputStream 字节类型文件输入输出流 (汉字显示乱码)
    Date 获取日期 SimpleDateFormat
    Random 随机生成数
    String StringBuffer Arrays 字符串修改 拼接
    Math
    装箱 拆箱Integer .ValueOf()
    LinkedListTest
    springboot cache
    耀眼的明星--项羽
    耀眼的明星--百年虚云
  • 原文地址:https://www.cnblogs.com/null00/p/5065437.html
Copyright © 2011-2022 走看看