How to count the trailing zeros in a binary number using Swift

1 Answer

0 votes
import Foundation

func countTrailingZeros(_ n: Int32) -> Int {
    if n == 0 {
        return 32 // All bits are zero for a 32-bit integer
    }

    var count = 0
    var number = n
    while (number & 1) == 0 {
        count += 1
        number >>= 1
    }
    
    return count
}

let number: Int32 = 80 // Binary: 1010000

print("Trailing zeros: \(countTrailingZeros(number))")



/*
run:

Trailing zeros: 4

*/

 



answered Jul 23, 2025 by avibootz
...