My solution works well for the test case that it shows is failing!


  • 0
    W

    Following test case fails for my Java code solution to this problem:-

    Input : 2147483648
    Expected : 1
    Actual : 0

    However, when I run the code in my system, it gives the correct output. I had to append "l" or "L" after the number though.

    public class NumberOfBits {
    	public static void main(String[] args) {
    		NumberOfBits ob = new NumberOfBits();
    		System.out.println(ob.hammingWeight(2147483648l));
    		System.out.println(ob.biggestPowerOf2(2147483648l));
    		System.out.println(2147483648l);
    	}
    	
    	// you need to treat n as an unsigned value
        public int hammingWeight(long m) {
        	long n = (long) m;
            int hammingWeight = 0;
    		while(n > 0) {
    			n -= Math.pow(2, biggestPowerOf2(n));
    			hammingWeight++;
    		}
    		return hammingWeight;
        }
        
        public int biggestPowerOf2(long n) {
    		int power = 0;
    		while (Math.pow(2, power) <= n) {
    			power++;
    		}
    		return --power;
    	}
    }
    

    I think the input should be appended with L to convert it to long, else the code would throw an error. I don't know how is the testing done internally, but I think my code should work.

    Any idea where am I going wrong?


Log in to reply
 

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