Today I wanted to challenge myself and try to write a function to determine if an integer is a power of N?
For example:
Input: 1
Output: true
Explanation: 2^0 = 1
Input: 16
Output: true
Explanation: 2^4 = 16
Input: 218
Output: false
Even though the Swift SDK has a built in functionality to accomplish this task, I was eager to challenge my Swift knowledge and see whether I can write this algorithm from scratch?
Could the input values be interpreted in a different way to achieve our objective?
import Foundation
func isPowerOf(n: Int, x: Int ) -> Bool {
return ((_abs(x) / n) % n == .zero)
}
//Could also use default Swift abs() method
func _abs( _ n: Int ) -> Int {
return n < 0 ? n * -1 : n
}
//Power Of Two
isPowerOf(n: 2, x: 1) //true
isPowerOf(n: 2, x: 16) //true
isPowerOf(n: 2, x: 8) //true
isPowerOf(n: 2, x: 218) //false
//Power Of Ten
isPowerOf(n: 10, x: 50) //false
isPowerOf(n: 10, x: 1500) // true
isPowerOf(n: 10, x: 30) //false
isPowerOf(n: 10, x: 23) //false