Last active
October 15, 2018 17:21
-
-
Save zflat/b692df71a164f46fbad286c8b85bdab5 to your computer and use it in GitHub Desktop.
sum the bits of an integer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
unsigned long bit_sum(unsigned long n) { | |
return n ? (1 + bit_sum(n & (n - 1))) : 0; | |
} | |
void main(int argc, char ** argv) { | |
char * p; | |
long n; | |
if(argc < 2) {exit(EXIT_FAILURE);} | |
n = strtol(argv[1], &p, 0); // see strotol manpage for error checking | |
if(*argv[1] == '\0' || *p != '\0') {exit(EXIT_FAILURE);} | |
printf("%ld\n", bit_sum(n)); | |
exit(EXIT_SUCCESS); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment