Problem overview
The method hammingWeight(_ n: Int) -> Int receives a non-negative integer and returns how many 1 bits its binary form has. This count is also called the Hamming weight.
For n = 11 the binary form is 1011, so the answer is 3. For n = 128, which is 10000000, the answer is 1. For n = 2147483645 the answer is 30: its binary form has 31 digits and exactly one of them is 0.
The lesson asks for O(k) time, where k is the number of 1 bits, and O(1) extra space.
Approach: remove the lowest 1 bit each pass
The obvious method checks all the bits one by one: look at the lowest bit, shift right, repeat. That takes a pass per bit position, including the 0s. The goal here is one pass per 1 bit.
The idea rests on what subtracting 1 does in binary. The lowest 1 bit becomes 0, every 0 below it becomes 1, and the higher bits stay the same. For example, 12 is 1100 and 11 is 1011. Now take the bitwise AND of the two numbers. Bits above the lowest 1 are the same in both, so they survive. The lowest 1 is 1 in n but 0 in n - 1, so it disappears. The bits below it are 0 in n, so they stay 0. The result, n & (n - 1), is n with its lowest 1 bit removed: 1100 & 1011 is 1000.
So repeat that operation until n becomes 0 and count the repetitions. Each repetition removes exactly one 1 bit, so the loop runs k times.
Step by step
- Copy
nintovar num. The loop changes it, and a Swift parameter is a constant. - Create
var countand start it at 0. - Loop while
num != 0. A number with no 1 bits left is 0. - Remove the lowest 1 bit with
num = num & (num - 1). - Add 1 to
countin the same pass: one bit was removed. - Return
countafter the loop.
The solution in Swift
class Solution {
func hammingWeight(_ n: Int) -> Int {
var num = n
var count = 0
while num != 0 {
num = num & (num - 1)
count += 1
}
return count
}
}
The Swift details worth a closer look:
Intis 64 bits. The values in this lesson fit in 31 bits, so the high bits are all 0 and never counted.- Precedence. The parentheses in
num & (num - 1)are not needed for precedence, since Swift's&binds tighter than most operators, but they make the intent clear. - Overflow traps. Swift arithmetic that overflows stops the program. With non-negative input,
num - 1never overflows: the smallest value it sees is 1, which becomes 0. - The parameter is a constant. Writing
n = n & (n - 1)directly is a compile error, which is why the code copies it tonum.
Tracing 11
Each pass for n = 11, with the binary form of num before and after:
1011 -> 1010
1010 -> 1000
1000 -> 0
Three passes, so the result is 3.
Complexity
Time: O(k). Each pass removes one 1 bit, so the loop runs exactly k times, at most 31 for the values allowed here.
Space: O(1). Only num and count are stored.
Edge cases and common mistakes
- Zero. The loop never runs and the result is 0.
- A power of two. There is a single 1 bit, so one pass is enough:
128gives 1. - All bits set.
2147483647, which is 31 ones, gives 31. - Negative input. The lesson only gives non-negative values. A negative
Inthas its sign bit set, so the loop eventually reaches the smallestInt, andnum - 1then overflows and crashes the program. - Using
|or^instead of&. Only AND removes the lowest 1 bit. - Forgetting to update
num. Computingnum & (num - 1)without assigning it back leavesnumunchanged, and the loop never ends.
Swift can count the bits directly with the nonzeroBitCount property: 11.nonzeroBitCount is 3. The loop above is the technique the lesson practises, and it is useful whenever you need to work with the lowest set bit.
Testing
n = 11gives3.n = 128gives1.n = 2147483645gives30.n = 0gives0.n = 2147483647gives31.n = 12gives2.
