Problem: Convert the given decimal whole number to hexadecimal.
Example:
decimal_to_hex(32)
20
decimal_to_hex(31)
1F
decimal_to_hex(6543)
198F
Solution in Python:
def decimal_to_hex(n):
"""
Author: Mayur P Srivastava
"""
"""
Author: Mayur P Srivastava
"""
if n == 0:
return "0";
hex_str = "";
while n > 0:
c = n % 16
n = n // 16
if c > 9:
c = chr(65 + c - 10)
else:
c = str(c)
hex_str = c + hex_str
return hex_str
Concepts Learned: Single loops, number systems
No comments:
Post a Comment