Skip to content
mgarcia edited this page Apr 16, 2012 · 6 revisions

Welcome to the snippets wiki!

number_of_ones

This file contains a function number_of_ones(n) that returns the number of ones found from the number 1 to n.

For instance:

number_of_ones(0) = 0
number_of_ones(1) = 1
number_of_ones(2) = 1
number_of_ones(10) = 2
number_of_ones(11) = 4
number_of_ones(12) = 5
...

An alternative for the internal function number_of_ones() is a perl one-liner:

$ perl -e '$sum += () = /1/g for 1..shift; print "NumberOfOnes=$sum\n"' 111
NumberOfOnes=36

But is less efficient.

Synopsis

$ perl number_of_ones.pl [num]
Clone this wiki locally