Java input test case : integer number too large: 2147483648


  • 0
    D

    Here is my Java Code, I translate it to C++, then it is AC.

    however, when I try to run it locally, it keeps on warning that 2147483648 is too large.
    (2147483648 is one of input test case number)

    public class ReverseBits {
    
        // you need treat n as an unsigned value
        public static int reverseBits(int n) {
    
            if(n==0) return 0;
    
            int result = 0;
    
            for(int i=0;i<32;i++){
                result |= ((n & (1<<(31-i)))>>(31-i))<<i;
            }
            return result;
        }
        
        public static void main(String[] args) {
            System.out.println(reverseBits(2147483648));
        }
    }

  • 1
    T

    Java don't have unsigned type. So it is a little different.

    First, 2147483648 is long in java. You need use Integer.parseUnsignedInt and Integer.toUnsignedString to handle unsigned values.

    Second, >> is right shift for signed int. Try >>>.


  • 1
    D

    right,

    so I think it is better to change default code definition to be "public long reverseBits(long n) {}" and limit input within unsigned int.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.