How to count the number of 1 bit in a given number with VB.NET

1 Answer

0 votes
Imports System

Public Class Program
	Public  Shared Function Count1Bit(ByVal n As Integer) As Integer
        Dim count As Integer = 0

        While n > 0
            count += n And 1
			n = n >> 1
        End While

        Return count
    End Function

	Public Shared Sub Main()
        Dim n As Integer = 95 ' 0101 1111
		
        Dim count As Integer = Count1Bit(n)
		
        Console.WriteLine("Number of 1 bit = " & count)
    End Sub
End Class




' run:
'
' Number of 1 bit = 6
'

 



answered Sep 13, 2021 by avibootz
edited Dec 4, 2021 by avibootz

Related questions

1 answer 175 views
2 answers 169 views
2 answers 151 views
1 answer 109 views
...