Skip to content

Commit a2efdcb

Browse files
Fix: use uint64_t for input and counter in countSetBits (TheAlgorithms#3003)
Co-authored-by: realstealthninja <[email protected]>
1 parent 2ea98ce commit a2efdcb

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

bit_manipulation/count_of_set_bits.cpp

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff 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
*/
3838
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
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));

0 commit comments

Comments
 (0)