java int溢出,结果只会保留低32位,高位会抛弃掉

  • Post author:
  • Post category:java


今天做leetcode题目时,发现int mid = 536848900,但是mid*mid=484528144,我说为啥程序运行一直出错呢!!

     int mid = 536848900;
        System.out.println(mid * mid);//484528144

        long mid2 = 536848900;//long * long
        System.out.println(mid2 * mid2);//288206741431210000

        System.out.println(Integer.MAX_VALUE);//2147483647
        System.out.println(Math.pow(2, 31) - 1);//2.147483647E9

        int a = Integer.MAX_VALUE;
//        a += 1;//-2147483648
        a += 100;//-2147483549

        long MonthNanoSeconds1 = 30 * 24 * 3600 * 1000 * 1000;//右边的结果是int,已溢出

        //int * long,与最后一个long型的1000相乘之前就已经溢出,所以结果也不对
        long MonthNanoSeconds2 = 30 * 24 * 3600 * 1000 * 1000L;

        //这是正确的写法
        long MonthNanoSeconds3 = 30L * 24 * 3600 * 1000 * 1000;//long * int

        System.out.println(MonthNanoSeconds1);//2134720512
        System.out.println(



版权声明:本文为u010002184原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。