PHP (38 bytes):
This uses the same aproach as my ES6 answer
<?=count(split(1,decbin($_GET[n])))-1;
This is a full code, you only need to put it in a file and access it over the browser, with the parameter n=<number>
.
PHP <4.2 (32 bytes):
This is a little shorter:
<?=count(split(1,decbin($n)))-1;
This only works reliably on PHP<4.2 because the directive register_globals
was set to Off
by default from PHP4.2 up to PHP5.4 (which was removed by then).
If you create a php.ini
file with register_globals=On
, this will work.
To use the code, access the file using a browser, with either POST or GET.
He gave 2 really good suggestions that have a very interesting use of the function array_sum
:
38 bytes:
<?=array_sum(str_split(decbin(1337)));
45 bytes:
<?=array_sum(preg_split('//', decbin(1337)));
This is a really great idea and can be shortened a bit more, to be 36 bytes long:
<?=array_sum(split(1,decbin(1337)));