.binary(digits:)

โฌ†๏ธ ้œ€่ฆ๏ผš str.pad()

extension BinaryInteger {
    /// binary digits of an integer. (array of strings)
    /// ```
    /// 5.binary()           // [          "1", "0", "1"]
    /// 5.binary(digits: 5)  // ["0", "0", "1", "0", "1"]
    /// ```
    public func binary(digits: Int? = nil) -> [String] {
        let str = String(self, radix: 2)
        var width = str.count
        if let digits = digits { width = digits }
        return str.pad("0", width).map { String($0) }
    }
}

Last updated