Java don't know why this fails.


  • 0
    T

    I don't know why this code fails. Can anyone help with this?

    with input of 1, i get the count of 2 instead of 1.

    public class Solution {
        // you need to treat n as an unsigned value
        public int hammingWeight(int n) {
            int count = 0;
            
            if (n%2 == 1) {
                count++;    
            }
            
            for (int i = 32; i > 2; i-- ) {
                if (n/(2^i) > 0) {
                    n = n-(2^i);
                    count++;
                }
            }
            return count;
        }
    }

  • 1
    R

    If you failed when it got to the 'big' number test cases, my best guess is that Java integers physically can't handle the input given. As far as my (personal) testing has gone with my code in my personal IDE (I use IntelliJ and its debugger), the code should be right for the range of values it can handle.

    Hope that helps, and correct me if I'm wrong!


  • 0

    1 is not big.


Log in to reply
 

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