convert a number from base 10 to base 2 in swift

One way to convert a number from decimal (base 10) to binary (base 2) in Swift is to use a simple algorithm that involves repeatedly dividing the decimal number by 2 and collecting the remainders. Here's an implementation of this algorithm:

main.swift
func decimalToBinary(_ decimal: Int) -> String {
    var quotient = decimal
    var binary = ""
    
    while quotient > 0 {
        let remainder = quotient % 2
        binary = "\(remainder)" + binary
        quotient = quotient / 2
    }
    
    return binary
}
267 chars
13 lines

Example usage:

main.swift
let decimalNumber = 42
let binaryNumber = decimalToBinary(decimalNumber)
print("Binary representation of \(decimalNumber) = \(binaryNumber)")
// Output: Binary representation of 42 = 101010
190 chars
5 lines

This algorithm works by repeatedly dividing the decimal number by 2 (the binary base) and collecting the remainders. The remainders represent the binary digits in reverse order, so we add them to the beginning of the binary string. Once the quotient becomes zero, we have collected all the binary digits and the binary string is complete.

gistlibby LogSnag