Bit Count in C
Level 4189 keystrokes
Counts the number of set bits (1s) in an integer using bitwise operations.
C code
// Function to count set bits1int countBits(unsigned int n) {2 int count = 0; // Loop until n becomes 03 while (n) { // n & 1 is the lowest bit (0 or 1); add it to count4 count += n & 1; // Shift right to check next bit5 n >>= 1;6 }7 return count;8}// 13 = 1101 in binary (3 ones)9printf("Bits in 13: %d\n", countBits(13));// 255 = 11111111 in binary (8 ones)10printf("Bits in 255: %d\n", countBits(255));Output
Bits in 13: 3 Bits in 255: 8
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this C code and how often they appear.
;× 6(× 6)× 6"× 4=× 3,× 2:× 2{× 2}× 2\× 2