why Integer.MAX_VALUE + 1 == Integer.MIN_VALUE?

后端 未结 8 1897
鱼传尺愫
鱼传尺愫 2020-11-27 06:57

System.out.println(Integer.MAX_VALUE + 1 == Integer.MIN_VALUE);

is true.

I understand that integer in Java is 32 bit and can\'t go above 23

8条回答
  •  囚心锁ツ
    2020-11-27 07:33

    Cause overflow and two-compliant nature count goes on "second loop", we was on far most right position 2147483647 and after summing 1, we appeared at far most left position -2147483648, next incrementing goes -2147483647, -2147483646, -2147483645, ... and so forth to the far most right again and on and on, its nature of summing machine on this bit depth.

    Some examples:

    int a = 2147483647;
    
    System.out.println(a);
    

    gives: 2147483647

    System.out.println(a+1);
    

    gives: -2147483648 (cause overflow and two-compliant nature count goes on "second loop", we was on far most right position 2147483647 and after summing 1, we appeared at far most left position -2147483648, next incrementing goes -2147483648, -2147483647, -2147483646, ... and so fores to the far most right again and on and on, its nature of summing machine on this bit depth)

    System.out.println(2-a); 
    

    gives:-2147483645 (-2147483647+2 seems mathematical logical)

    System.out.println(-2-a);
    

    gives: 2147483647 (-2147483647-1 -> -2147483648, -2147483648-1 -> 2147483647 some loop described in previous answers)

    System.out.println(2*a);
    

    gives: -2 (2147483647+2147483647 -> -2147483648+2147483646 again mathematical logical)

    System.out.println(4*a);
    

    gives: -4 (2147483647+2147483647+2147483647+2147483647 -> -2147483648+2147483646+2147483647+2147483647 -> -2-2 (according to last answer) -> -4)`

提交回复
热议问题