Skip to content

Instantly share code, notes, and snippets.

@loganwright
Last active August 29, 2015 14:13
Show Gist options
  • Save loganwright/f4586f25aa475ea52b04 to your computer and use it in GitHub Desktop.
Save loganwright/f4586f25aa475ea52b04 to your computer and use it in GitHub Desktop.
Programming Puzzles

Count the number of binary 1 flags for a given positive integer. For instance:

1 = 0b1 => 1 bit 2 = 0b10 => 1 bit 3 = 0b11 => 2 bits

Recursively

func countBitsRec(var n: NSInteger) -> NSInteger {
    return n == 0 ? 0 : n & 1 + countBits(n >> 1)
}

countBitsRec(1898)

Iteratively

func countBits(var n: NSInteger) -> NSInteger {
    var numberOfBits = 0
    while n != 0 {
        if n & 1 == 1 {
            numberOfBits++;
        }
        numberOfBits
        n >>= 1
    }
    return numberOfBits
}

countBits(1)

Reverse a given positive integer using only mathematics w/o strings or arrays. For instance:

1234 => 4321 5629 => 9265

func reverse(var n: Int) -> Int {
    if n < 10 {
        return n
    }
    var left = n / 10
    var right = n - (left * 10)
    var length = ceil(log10(Double(n)))
    length = pow(10.0, length - 1)
    return right * Int(length) + reverse(left)
}

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