Skip to content

Instantly share code, notes, and snippets.

@swift-student
Created March 25, 2020 15:33
Show Gist options
  • Save swift-student/b67514e0716007eaeebdfc5a6c493aef to your computer and use it in GitHub Desktop.
Save swift-student/b67514e0716007eaeebdfc5a6c493aef to your computer and use it in GitHub Desktop.

To start with, I will need to figure out how to get a binary representation of an integer. Then I will simply loop through the numbers higher and lower until I find an integer that has the same number of 1's or I hit Int.max or Int.min. I will then return these numbers in a tuple.

Once I had completed my function, I realized that I should have been using UInt instead of Int as the instructions said it should take in a positive integer, so I switched all my code to be working with UInts. I ended up making a couple extensions, that made finding the nubmer of "1"s in the binary representation much shorter to write. Then it was just a matter of creating two for loops, one going up, and one going down to find the next highest and lowest integers with the same number of "1"s in their binary string.

This is my result:

func sameNumberOfBinaryOnes(_ number: UInt) -> (higher: UInt?, lower: UInt?) {
    let numBinaryOnes = number.numBinaryOnes
    
    var higher: UInt? = nil
    var lower: UInt? = nil
    
    for h in number + 1...UInt.max {
        if h.numBinaryOnes == numBinaryOnes {
            higher = h
            break
        }
    }
    
    for l in stride(from: number - 1, to: UInt.min, by: -1) {
        if l.numBinaryOnes == numBinaryOnes {
            lower = l
            break
        }
    }
    
    return (higher, lower)
}

extension UInt {
    var binaryRep: String {
        String(self, radix: 2)
    }
    
    var numBinaryOnes: UInt {
        UInt(self.binaryRep.filter { $0 == "1" }.count)
    }
}

sameNumberOfBinaryOnes(12) // (higher 17, lower 10)
sameNumberOfBinaryOnes(28) // (higher 35, lower 26)
sameNumberOfBinaryOnes(3)  // (higher 5, nil)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment