Skip to content

Instantly share code, notes, and snippets.

@mredig
Last active June 19, 2019 15:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mredig/cc0f5ac43770da6563b9a0b67b021a43 to your computer and use it in GitHub Desktop.
Save mredig/cc0f5ac43770da6563b9a0b67b021a43 to your computer and use it in GitHub Desktop.
takes any positive integer as an argument and returns the next highest and next lowest integers having the same number of 1s as the passed argument's binary representation
import Foundation
extension FixedWidthInteger {
func sameNumberOfBinaryOnes() -> (Self?, Self?) {
guard self != 0 else { return (nil,nil) }
let myCount = binaryOneCount()
var nextHigher: Self?
for maybe in (self + 1)...Self.max {
if myCount == maybe.binaryOneCount() {
nextHigher = Self(maybe)
break
}
}
// keeping just as an example of my first iteration
// var counter = self + 1
// while counter.binaryOneCount() != myCount {
// counter += 1
// }
// nextHigher = counter
var nextLower: Self?
for maybe in (0..<self).reversed() {
if myCount == maybe.binaryOneCount() {
nextLower = Self(maybe)
break
}
}
return (nextHigher, nextLower)
}
func toBinaryString() -> String {
return String(self, radix: 2)
}
private func binaryOneCount() -> Int {
let str = toBinaryString()
let before = str.count
let after = str.replacingOccurrences(of: "1", with: "").count
return before - after
}
}
12.sameNumberOfBinaryOnes()
28.sameNumberOfBinaryOnes()
3.sameNumberOfBinaryOnes()
2.sameNumberOfBinaryOnes()
1.sameNumberOfBinaryOnes()
0.sameNumberOfBinaryOnes()
@mredig
Copy link
Author

mredig commented Jun 19, 2019

edited to make generic for all int variants

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment