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 {
3636 * @returns total number of set-bits in the binary representation of number `n`
3737 */
3838std::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
4040 // 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.
4151
42- int count = 0 ; // "count" variable is used to count number of set-bits('1')
43- // in binary representation of number 'n'
4452 while (n != 0 ) {
4553 ++count;
4654 n = (n & (n - 1 ));
You can’t perform that action at this time.
0 commit comments