Creative Commons License
This work is licensed under a Creative Commons Attribution 3.0 Unported License.

Tuesday, May 7, 2013

Decimal to Binary


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