Last active
September 18, 2019 23:39
-
-
Save bradleyyin/4c27ece9b18c6c3d765a01474c5f14f6 to your computer and use it in GitHub Desktop.
morning code challenge week 11
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
func sameNumberOfBinaryOnes(_ number: Int) -> (Int, Int?) { | |
let stringNumInBinary = "\(number, radix: .binary)" | |
var numOfOneInNum: Int = 0 | |
for element in stringNumInBinary { | |
if element == "1" { | |
numOfOneInNum += 1 | |
} | |
} | |
var highNum: Int = 0 | |
var lowNum: Int? | |
for i in number + 1 ..< Int.max { | |
let iStringBinary = "\(i, radix: .binary)" | |
var numOfOne: Int = 0 | |
for element in iStringBinary { | |
if element == "1" { | |
numOfOne += 1 | |
} | |
} | |
if numOfOneInNum == numOfOne { | |
highNum = i | |
break | |
} | |
} | |
for i in stride(from: number - 1, through: 1, by: -1) { | |
let iStringBinary = "\(i, radix: .binary)" | |
var numOfOne: Int = 0 | |
for element in iStringBinary { | |
if element == "1" { | |
numOfOne += 1 | |
} | |
} | |
if numOfOneInNum == numOfOne { | |
lowNum = i | |
break | |
} | |
} | |
return(highNum, lowNum) | |
} | |
public extension String.StringInterpolation { | |
/// Represents a single numeric radix | |
enum Radix: Int { | |
case binary = 2, octal = 8, decimal = 10, hex = 16 | |
/// Returns a radix's optional prefix | |
var prefix: String { | |
return [.binary: "0b", .octal: "0o", .hex: "0x"][self, default: ""] | |
} | |
} | |
/// Return padded version of the value using a specified radix | |
mutating func appendInterpolation<I: BinaryInteger>(_ value: I, radix: Radix, prefix: Bool = false, toWidth width: Int = 0) { | |
// Values are uppercased, producing `FF` instead of `ff` | |
var string = String(value, radix: radix.rawValue).uppercased() | |
// Strings are pre-padded with 0 to match target widths | |
if string.count < width { | |
string = String(repeating: "0", count: max(0, width - string.count)) + string | |
} | |
// Prefixes use lower case, sourced from `String.StringInterpolation.Radix` | |
if prefix { | |
string = radix.prefix + string | |
} | |
appendInterpolation(string) | |
} | |
} | |
sameNumberOfBinaryOnes(12) | |
sameNumberOfBinaryOnes(28) | |
sameNumberOfBinaryOnes(3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment