Problem: Convert the given decimal integer to binary.
Example:
decimal_to_binary(5)
101
decimal_to_binary(11)
1011
decimal_to_binary(35)
100011
Solution in Python:
def decimal_to_binary(n):
"""
Author: Mayur P Srivastava
"""
if n == 0:
return "0";
binary_str = "";
while n > 0:
bit = n % 2
n = n // 2
binary_str = str(bit) + binary_str
return binary_str
Concepts Learned: Single loops, binary numbers.
No comments:
Post a Comment