Created
January 14, 2019 16:44
-
-
Save AustinBCole/c71fca9e1645a31938585b1a0469bcf2 to your computer and use it in GitHub Desktop.
This file contains 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
Assumptions: | |
I'll assume that I can be passed a negative integer, so I will guard against it. | |
Cases: | |
0 -> "0" | |
1 -> "1" | |
2 -> "10" | |
21 -> "10101" | |
30 -> "11110" | |
Implementation: | |
I am going to use while loops to check if the number yields a positive result when subtracted by each of the five binary gate | |
numbers, starting with 16 and going down to 1. I will then have a switch statement that will add on a number of zeros depending | |
on how big the number was originally and how many gates it took to reach the number. | |
Code: | |
func toBinaryString(num: Int) -> String { | |
var binaryString = "" | |
guard num > 0 else {return "0"} | |
var number = num | |
if number - 16 >= 0 { | |
number -= 16 | |
binaryString += "1" | |
} else if binaryString.count == 0 { | |
binaryString += "0" | |
} | |
if number - 8 >= 0 { | |
number -= 8 | |
binaryString += "1" | |
} else if binaryString.count == 0 || binaryString.count == 1 { | |
binaryString += "0" | |
} | |
if number - 4 >= 0 { | |
number -= 4 | |
binaryString += "1" | |
} else if binaryString.count == 0 || binaryString.count == 1 || binaryString.count == 2{ | |
binaryString += "0" | |
} | |
if number - 2 >= 0 { | |
number -= 2 | |
binaryString += "1" | |
} else if binaryString.count == 0 || binaryString.count == 1 || binaryString.count == 2 || binaryString.count == 3{ | |
binaryString += "0" | |
} | |
if number - 1 >= 0 { | |
number -= 1 | |
binaryString += "1" | |
} else if binaryString.count == 0 || binaryString.count == 1 || binaryString.count == 2 || binaryString.count == 3 || binaryString.count == 4{ | |
binaryString += "0" | |
} | |
while binaryString.first == "0" { | |
binaryString.removeFirst() | |
} | |
return binaryString | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment