Why casting n to long type does not work


  • 1
    P

    This code gets Accepted..

    public class Solution {
        // you need to treat n as an unsigned value
        public int hammingWeight(int n) {
            int count=0;
            while (n != 0){
                if ( ( n & 1) == 1) count++;
                n = n >>>1;
            }
            return count;
        }
    }
    

    while casting n to long (for following code) get wrong answer for input 2147483648 (10000000000000000000000000000000). can somebody explain me why?

    public class Solution {
        // you need to treat n as an unsigned value
        public int hammingWeight(int m) {
            int count=0;
            long n = m;
            while (n != 0){
                if ( ( n & 1) == 1) count++;
                n = n >>>1;
            }
            return count;
        }
    }

Log in to reply
 

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