Skip to content

Instantly share code, notes, and snippets.

@ming-chu
Last active May 31, 2019 01:16
Show Gist options
  • Save ming-chu/723e0da010be8e3dbe6ee094a2dd02c2 to your computer and use it in GitHub Desktop.
Save ming-chu/723e0da010be8e3dbe6ee094a2dd02c2 to your computer and use it in GitHub Desktop.
Check a +ve Int is 2^n where n is non -ve Int
//Check a +ve Int is 2^n where n is non -ve Int
func check(_ i: Int) -> Bool {
guard i != 1 else { return true }
guard i % 2 == 0 else { return false }
return check(i / 2)
}
print(check(1024))
print(check(1023))
/*
for i in (0...1024) {
print("\(i) is \(check(i))")
}
*/
func check2(_ i: Int) -> Bool {
return String(i, radix: 2).filter({ $0 == "1" }).count == 1
}
print(check2(1024))
print(check2(1023))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment