티스토리 뷰

728x90

String Formatting

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

Function Description

Complete the print_formatted function in the editor below.

print_formatted has the following parameters:

  • int number: the maximum value to print

Prints

The four values must be printed on a single line in the order specified above for each i from 1 to number. 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.

Input Format

A single integer denoting n.

Constraints

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

 

문제해석

input으로 1~99 사이의 정수 n값을 입력받는다. Decimal, Octal, Hexadecimal(capitalized), Binary 4개의 값을 1~n까지 반복하여 출력한다. 이 때 정렬은 2진수의 길이에 맞게 공간을 확보하고 오른쪽으로 정렬하여 출력한다.

 

문제풀이

우선 정렬을 위해 2진수의 길이를 구해야 하는데, 2진수 값 중에서도 가장 긴 길이를 기준으로 하면 된다. 그래서 w = len(bin(number)[2:]) 코드를 사용하여 입력된 n값(최대값)을 이진수로 변환하여 그 길이를 구하였다. bin(number)[2:]와 같이 [2:]를 하는 이유는 8진수의 경우에는 0o, 16진수의 경우에는 0x, 2진수의 경우에는 0b라는 값이 앞에 붙기 때문에 이것을 제거해 주기 위해서다.

그리고 나서는 for문을 사용하여 1~n까지 루프를 돌면서 10진수, 8진수, 16진수, 2진수를 각각 구한다. str()로 타입변환을 하는 이유는 출력할 때 rjust()함수를 사용하기 위해서다.

def print_formatted(number):
    # your code goes here    
    w = len(bin(number)[2:])    
    for i in range(1, number+1):
        v_dec = str(i)
        v_oct = str(oct(i)[2:])
        v_hex = str(hex(i)[2:].upper())
        v_bin = str(bin(i)[2:])        
               
        print(v_dec.rjust(w, ' '), v_oct.rjust(w, ' '), v_hex.rjust(w, ' '), v_bin.rjust(w, ' '))
          

if __name__ == '__main__':
    n = int(input())
    print_formatted(n)

 

728x90
LIST
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함