Skip to content

Instantly share code, notes, and snippets.

@marlonjames71
Last active July 17, 2020 15:55
Show Gist options
  • Save marlonjames71/786b08c72dba9d8b999701999040cf1a to your computer and use it in GitHub Desktop.
Save marlonjames71/786b08c72dba9d8b999701999040cf1a to your computer and use it in GitHub Desktop.
Same Binary Ones
func sameNumberOfBinaryOnes(number: Int) -> (Int, Int)? {
let binary = 2
let numberBinary = String(number, radix: binary)
var pairedBinaries: (first: Int, second: Int)? = nil
for matchingNumber in stride(from: number, through: 0, by: -1) {
let matchingNumberBinary = String(matchingNumber, radix: binary)
if matchingNumberBinary == numberBinary {
pairedBinaries?.first = matchingNumber
break
}
}
for secondMatchingNumber in stride(from: number, through: number * number, by: 1) {
let matchingNumberBinary = String(secondMatchingNumber, radix: binary)
if matchingNumberBinary == numberBinary {
pairedBinaries?.second = secondMatchingNumber
break
}
}
return pairedBinaries
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment