Number of 1 Bits

Solution in Go

Convert the number to binary and while doing so keep counting the 1s

func hammingWeight(num uint32) int {
    total := 0

    for num > 0 {
        if num % 2 == 1 {
            total++
        }

        num = num / 2
    }

    return total
}
Subscribe via email

Get notified once/twice per month when new articles are published.

Copyright © 2022 - 2024 TheDeveloperCafe.
The Go gopher was designed by Renee French.