여니의 취준 준비/코딩테스트 (Python)

[Python] n1212번 | 8진수 2진수

여니's 2021. 4. 26. 23:22


# n = int(input())
# array = []
#
# while n > 1:
#     result = n % 2
#     n = n // 2
#     array.append(result)
# array.append(1)
#
# index = len(array)
# for i in range(index - 1, -1, -1):
#     print(array[i],end='')

처음에 파이썬 내에 진수변환해주는 내장함수의 존재는 새까맣게 잊은채,,

빡구현을 시전한 과거의 나 자신,,

반성해 반성해 ㅠㅠ

8진수 입력 받아놓고 10진수로 계산함,, 바부 ㅠㅠ 

 

 

학교 전공수업 때 배웠었는데,

그새 까먹어서

다시 복습 ^0^

 

# 다른 진수 -> 10진수로 변환
b=int('0b1010',2)
o=int('0o12',8)
h=int('0xa',16)​

int함수를 이용하면,  다른 진수 -> 10진수로 손쉽게 변환 가능!

 

10진수 -> 다른진수

bin(int값), oct(int값), hex(int값)

또는 format(int값,'#b or b') -> #b (2진수), #o (8진수), #x(16진수)

 

# 10진수 -> 2진수, 8진수, 16진수 변환
# 1. bin(), oct(), hex() 내장함수 활용 | 2진수 : bin, 8진수 : oct, 16진수 : hex
value=10
b=bin(value) #ob1010
o=oct(value) #0o12
h=hex(value) #0xa

# 2. format() 내장함수 사용
value=10
b=format(value,'#b')
b=format(value,'b') # 0b 제거
o=format(value,'#o')
o=format(value,'o') # 0o 제거
h=format(value,'#h')
h=format(value,'h') # 0x 제거
# 다른 진수 -> 다른 진수로 변환
# ex1) 2진수 -> 8진수
o=oct(0b111100) #oct(2진수)
# ex2) 2진수 -> 16진수
h=hex(0b11100) #hex(2진수)
# ex3) 2진수 -> 10진수
s=str(0b11100) #str(2진수)

n1212번 답안코드

b=int(input(),8)
print(bin(b)[2:])

8진수 -> 10진수 -> 2진수

1) 8진수 -> 10진수

: int를 이용한다.

b=int(input(),8)

 

b에는 10진수가 들어있다.

 

2) 10진수 -> 2진수

bin 함수 이용

print(bin(b)[2:])

0b는 출력 안되게 해야하니까,

[2:] 슬라이싱 이용해서 해결!


def change(num, first = False):
    ret = ''  # 문자열 초기화
    while num: 
        ret += chr(num % 2 + 48) #아스키코드, 48 : '0', 49 :'1'
        num //= 2
    while len(ret) < 3: # 3자리 이하면, 오른쪽 끝에부터 '0' 추가
        ret += '0'

    idx = 3
    if first: # 맨 처음 숫자일 때 (0b 제거작업)
        while idx > 1 and ret[idx - 1] == '0':
            idx -= 1
    return ret[:idx][::-1]

N = input()
isFirst = True # 0b를 없애주기 위해 필요한 변수
# 8진수 314를 2진수로 변환하기 위해서는, 3 | 1 | 4 각각 나눠준 뒤, 3을 2진수로, 1을 2진수로 바꿔주면 끝!
for i in range(len(N)):
    print(change(int(N[i]), isFirst),end='')
    isFirst = False #처음에만 작동하고, 그 이후엔 작동 x

 

 

해답 출처 :github.com/tony9402/baekjoon/blob/main/solution/implementation/1212/main.py

 

tony9402/baekjoon

코딩테스트 대비 문제집(Baekjoon Online Judge). Contribute to tony9402/baekjoon development by creating an account on GitHub.

github.com


www.acmicpc.net/problem/1212

 

1212번: 8진수 2진수

첫째 줄에 8진수가 주어진다. 주어지는 수의 길이는 333,334을 넘지 않는다.

www.acmicpc.net