String Formatting - Hacker Rank Solution
Given an integer, , print the following values for each integer from to :
Input Format
A single integer denoting .
Constraints
Output Format
Print lines where each line (in the range ) contains the respective decimal, octal, capitalized hexadecimal, and binary values of . Each printed value must be formatted to the width of the binary value of .
Sample Input
17
Sample Output
1 1 1 1
2 2 2 10
3 3 3 11
4 4 4 100
5 5 5 101
6 6 6 110
7 7 7 111
8 10 8 1000
9 11 9 1001
10 12 A 1010
11 13 B 1011
12 14 C 1100
13 15 D 1101
14 16 E 1110
15 17 F 1111
16 20 10 10000
17 21 11 10001 Solution: this solution is for python3
def print_formatted(number):
final_number = ''
width = len(bin(number).split("b")[1])
for i in range(1,number+1):
inti = str(int(i))
octant = str(oct(i).split("o")[1])
hexnumber = str(hex(i).split("x")[1]).upper()
binnumber = str(bin(i).split("b")[1])
final_number = f'{str.rjust(inti,width)} {str.rjust(octant, width)}
{str.rjust(hexnumber, width)}
{str.rjust(binnumber, width)} '
print(final_number)
if __name__ == '__main__':
n = int(input())
print_formatted(n)
Comments
Post a Comment