File tree Expand file tree Collapse file tree 1 file changed +11
-3
lines changed Expand file tree Collapse file tree 1 file changed +11
-3
lines changed Original file line number Diff line number Diff line change @@ -36,11 +36,19 @@ namespace count_of_set_bits {
36
36
* @returns total number of set-bits in the binary representation of number `n`
37
37
*/
38
38
std::uint64_t countSetBits (
39
- std ::int64_t n) { // int64_t is preferred over int so that
39
+ std ::uint64_t n) { // uint64_t is preferred over int so that
40
40
// no Overflow can be there.
41
+ // It's preferred over int64_t because it Guarantees that inputs are always non-negative,
42
+ // which matches the algorithmic problem statement.
43
+ // set bit counting is conceptually defined only for non-negative numbers.
44
+ // Provides a type Safety: Using an unsigned type helps prevent accidental negative values,
45
+
46
+ std::uint64_t count = 0 ; // "count" variable is used to count number of set-bits('1')
47
+ // in binary representation of number 'n'
48
+ // Count is uint64_t because it Prevents theoretical overflow if someone passes very large integers.
49
+ // Behavior stays the same for all normal inputs.
50
+ // Safer for edge cases.
41
51
42
- int count = 0 ; // "count" variable is used to count number of set-bits('1')
43
- // in binary representation of number 'n'
44
52
while (n != 0 ) {
45
53
++count;
46
54
n = (n & (n - 1 ));
You can’t perform that action at this time.
0 commit comments