Proper solution in the Interview

So... I was trying to solve this problem Number-of-1-bits.

So, I solved it this way:

class Solution:
    def hammingWeight(self, n: int) -> int:
        string_num = str(bin(n))
        
        cnt = 0
        
        for char in string_num:
            if char == "1":
                cnt += 1
                
        return cnt

Though I could do this simply:

class Solution:
    def hammingWeight(self, n: int) -> int:
        return bin(n).count("1")

The 0th solution beats almost 91% of all Python solution.

But is this the correct approach in the interview?

With this solution, am I likely to pass or the recruiter wants "algorithmic" solution?

This problem has another solution with Brian Karnighan's algorithm which deals with the bit-wise opeartion.

class Solution:
    def hammingWeight(self, n: int) -> int:
        cnt = 0
        
        while(n != 0):
            n &= (n-1)
            
            cnt += 1
        
        return cnt

So the interviewer will want to see something like this or with my kinda solution I can pass?

Comments (0)