Last active
May 31, 2019 01:16
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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