String Formatting | HackerRank
String Formatting | HackerRank
Print the formatted decimal, octal, hexadecimal, and binary values for $n$ integers.
www.hackerrank.com
Goal
given an integer, n, print the following values for each integer i from 1 to n:
1. Decimal
2. Octal
3. Hexadecimal (capitalized)
4. Binary
Each value should be space-padded to match the width of the binary value of number and the values should be separated by a single space.
Solution
In this script, we have a function called print_formatted which takes an integer number as input.
The function then sets the maximum width of the binary representation of number and initializes an empty string called text.
The function then uses a for loop to iterate through the range from 1 to number.
Inside the loop, it adds the right-justified string of the current number in decimal, octal, hexadecimal, and binary format to the text string.
The right-justified strings are created using the rjust method which takes an integer argument indicating the minimum width of the resulting string.
By adding 1 to the max_width variable, we create a space between the formatted strings.
After constructing the text string for each value of i, the function prints it to the console and then resets the text string to an empty string.
# String Formatting
def print_formatted(number):
# your code goes here
binary_max = str(bin(number))
max_width = len(binary_max[2:])
text = ""
for i in range(1, number + 1):
text += str(i).rjust(max_width)
text += str(oct(i))[2:].rjust(max_width + 1)
text += str(hex(i))[2:].upper().rjust(max_width + 1)
text += str(bin(i))[2:].rjust(max_width + 1)
print(text)
text = ""
if __name__ == '__main__':
n = int(input())
print_formatted(n)'software Engineering > (Python)HackerRank' 카테고리의 다른 글
| [Python] HackerRank - itertools.product() (0) | 2023.02.21 |
|---|---|
| [Python] HackerRank - Capitalize! (0) | 2023.02.19 |
| [Python] HackerRank - Text Wrap (0) | 2023.02.17 |
| [Python] HackerRank - String Validators (0) | 2023.02.16 |
| [Python] HackerRank - Find a string (0) | 2023.02.15 |