Code Explanation:
1. Function Definition
def dec_to_bin(n):
This defines a function dec_to_bin that takes an integer n.
The function’s goal is to convert a decimal number (n) to its binary representation using recursion.
2. Base Case: When n is 0
if n == 0:
return ""
This is the base case for the recursive function.
When n becomes 0, return an empty string.
This stops the recursion and begins building the final binary string.
3. Recursive Case: Divide and Conquer
return dec_to_bin(n // 2) + str(n % 2)
This line performs the core recursive logic:
n // 2: Divides the number by 2 (integer division), moving toward the base case.
Recursive call: Converts the quotient into binary.
n % 2: Gets the remainder, which is either 0 or 1—this is the current binary digit.
Combines: Appends the current binary digit to the end of the binary string returned from the recursive call.
4. Function Call and Output
print(dec_to_bin(10))
Let’s walk through what happens step-by-step for dec_to_bin(10):
Step-by-step breakdown:
dec_to_bin(10)
= dec_to_bin(5) + "0"
= (dec_to_bin(2) + "1") + "0"
= ((dec_to_bin(1) + "0") + "1") + "0"
= (((dec_to_bin(0) + "1") + "0") + "1") + "0"
= ((("" + "1") + "0") + "1") + "0"
= ("1" + "0") + "1" + "0"
= "10" + "1" + "0"
= "1010"
Final Output
1010
The binary representation of decimal 10 is 1010.
.png)

0 Comments:
Post a Comment