Not the optimal answer, but want to know why not working


  • 0
    G

    Can someone explain to me why this cannot be the answer? What's the proper way to deal with unsigned integers here?

    public class Solution {
        // you need to treat n as an unsigned value
        public int hammingWeight(int n) {
            int num = 0;
            
            for (int i = 0; i < 32; i++) 
            {
                if (n % 2 == 1) {
                    num++;   
                }
                n = n >> 1; 
            }
            return num;
        }
    }xa
    ```![alt text](image url)

  • 1
    O

    Hi @grace6, there are two things you need to change in your code:

    First, if you only check n % 2 == 1, you are assuming n has a 0 as its left-most bit (n is positive). However, counter cases can be when n < 0, where you need to also check n % 2 == -1. Therefore, simply change the if condition check to (n % 2 != 0) will work for your approach.

    Second, again, since n is an unsigned value, which means its left-most bit does not serve for signedness, if you update n = n >> 1, in cases where n < 0, you are not shifting its left-most bit if it is a 1 (since >> preserves signedness). Therefore, you need to change it to n = n >>> 1 (aka. logical shift).

    Finally, you will have:

        public int hammingWeight(int n) {
            int num = 0;
            
            for (int i = 0; i < 32; i++) 
            {
                if (n % 2 != 0) { //only if the current n is odd (n % 2 == 1 or -1), increment num
                    num++;   
                }
                n = n >>> 1;   //shift n to right regardless of its signedness
            }
            return num;
        }
    

    If anyone has different ideas, please feel free correct me :) hope it helps


  • 0
    G

    wow thanks @Oaixoul for the nice explanation! I should have consider negative numbers and the difference between the logical and arithmatic shifts!


Log in to reply
 

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