How to count the number of set bits in an integer in Swift

1 Answer

0 votes
import Foundation

func countSetBits(_ n: Int) -> Int {
    var count = 0
    var num = n
    while num > 0 {
        count += num & 1
        num >>= 1
    }
    return count
}

let num = 445; // 0001 1011 1101

print("The number of set bits in \(num) is \(countSetBits(num))")


 
/*
run:
 
The number of set bits in 445 is 7

*/

 



answered Dec 10, 2024 by avibootz

Related questions

1 answer 95 views
1 answer 93 views
2 answers 153 views
2 answers 131 views
...