Why the code can't pass the test case when n = 2^32?

  • 0
    public int reverseBits(int n){
    	List<Integer> list = new ArrayList<Integer>();
    	int ans = 0;
    	while( n > 0){
    		list.add(n % 2);
    		n = n/2;
    	for(int i=list.size()+1; i<=32; i++){
    	for(int i=0; i<list.size(); i++){
    		ans = ans * 2 + list.get(i);
    	return ans;
    Input:2147483648 (10000000000000000000000000000000)
    Output:0 (00000000000000000000000000000000)
    Expected:1 (00000000000000000000000000000001)

  • 0

    @chenqun1218 You have defined your answer(ans) as an integer. An integer value uses the highest bit (leftmost bit ) to store the sign value. The max value an int32 can store is 2147483647. So the input you have provided(which is also int) is not 2147483648 but -0. Define your variable ans as unsigned and your code will work fine.

Log in to reply

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