Last active
November 25, 2020 18:07
-
-
Save mahdimaymandi/edcd98bfd0ef9dbc2a4e3365189dc321 to your computer and use it in GitHub Desktop.
Python Decimal To Binary
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
import math | |
def toBinary(num): | |
powers = [] | |
while num > 0: | |
power = int(math.log(num)/math.log(2)) | |
powers.append(power) | |
num -= pow(2, power) | |
i = 0 | |
binaryString = "" | |
while len(powers) > 0: | |
if (i in powers): | |
binaryString = "1" + binaryString | |
powers.remove(i) | |
else: | |
binaryString = "0" + binaryString | |
i += 1 | |
return binaryString |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment