Number of 1's in binary expansion of n

From Rosetta Code
Revision as of 04:55, 11 April 2021 by CalmoSoft (talk | contribs) (Created page with "{{Draft task}} ;Task: Show the number of 1's in binary expansion of n, where '''0 <= n < 50''' <br><br> =={{header|Ring}}== <lang ring> load "stdlib.ring" decimals(0) see...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Number of 1's in binary expansion of n is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.
Task

Show the number of 1's in binary expansion of n, where 0 <= n < 50

Ring

<lang ring> load "stdlib.ring"

decimals(0) see "working..." + nl

decList = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] baseList = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"]

row = 0 limit = 49

for n = 0 to limit

   num = 0
   nbin = decimaltobase(n,2)
   for m = 1 to len(nbin)
       if nbin[m] = "1"
          num = num + 1
       ok
   next
   row = row + 1
   see "" + num + " "
   if row%10 = 0
      see nl
   ok

next

see "done..." + nl

func decimaltobase(nr,base)

    binList = [] 
    binary = 0
    remainder = 1
    while(nr != 0)
         remainder = nr % base
         ind = find(decList,remainder)
         rem = baseList[ind]
         add(binList,rem)
         nr = floor(nr/base) 
    end
    binlist = reverse(binList)
    binList = list2str(binList)
    binList = substr(binList,nl,"")  
    return binList

</lang>

Output:
working...
0 1 1 2 1 2 2 3 1 2 
2 3 2 3 3 4 1 2 2 3 
2 3 3 4 2 3 3 4 3 4 
4 5 1 2 2 3 2 3 3 4 
2 3 3 4 3 4 4 5 2 3 
done...