#Scheme#
Scheme
I polished the rules a bit to add to the challenge. The function doesn't care about the base of the number because it uses its own binary scale. I was inspired by the way analog to numeric conversion works. I just use plain recursion for this:
(define (find-ones n)
(define (nbits n)
(let nbits ([i 2])
(if (< i n) (nbits (* i 2)) i)))
(let f ([half (/ (nbits n) 2)] [i 0] [n n])
(cond [(< half 2) i]
[(< n i) (f (/ half 2) i (/ n 2))]
[else (f (/ half 2) (+ i 1) (/ n 2))])))