Skip to content

Instantly share code, notes, and snippets.

@NathanJang
Last active November 5, 2015 01:08
Show Gist options
  • Save NathanJang/f02e0aa576079c4f065e to your computer and use it in GitHub Desktop.
Save NathanJang/f02e0aa576079c4f065e to your computer and use it in GitHub Desktop.
func isEven(number: Int) -> Bool {
return number % 2 == 0
}
//isEven(31)
func isDivisible(x: Int, by y: Int) -> Bool {
return x % y == 0
}
//isDivisible(30, by: 5)
/// DON'T EVER DO THIS BECAUSE THIS IS INEFFICIENT AF
func numberOfDigitsByConvertingToString(x: Int) -> Int {
return String(x).characters.count
}
//numberOfDigitsByConvertingToString(1100000)
func numberOfDigits(x: Int) -> Int {
var temporaryValue = x;
var count = 0
while temporaryValue != 0 {
temporaryValue /= 10
count++
}
return count
}
//numberOfDigits(1100000)
func fizzBuzz(fizzAt fizz: Int, buzzAt buzz: Int, max: Int) {
for count in 1...max {
if count % (fizz * buzz) == 0 {
print("FizzBuzz")
} else if count % fizz == 0 {
print("Fizz")
} else if count % buzz == 0 {
print("Buzz")
} else {
print("\(count)")
}
}
}
//fizzBuzz(fizzAt: 3, buzzAt: 5, max: 69)
/// This is an interesting method to do it but it's harder to understand.
/// You don't have to worry about it yet, probably no one does something like this in real apps.
/// For 3 and 5 only.
func bitwiseFizzBuzz(max max: Int) {
var mutatingMask = 0b110000010010010000011000010000
let messages: [String?] = [ nil, "Fizz", "Buzz", "FizzBuzz" ]
for count in 1...max {
let index = mutatingMask & 3
if let message = messages[index] {
print(message)
} else {
print(count)
}
mutatingMask = mutatingMask >> 2 | index << 28
}
}
//bitwiseFizzBuzz(max: 69)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment