반응형
문제
https://www.acmicpc.net/problem/16506
16506번: CPU
디지털하드웨어설계 과목의 최종 프로젝트는 16-bit CPU를 설계하고 Verilog 언어로 구현하는 것이다. 본인이 구현한 CPU가 제대로 동작하는지 테스트하기 위해서는 기계어 코드를 입력으로 주어야
www.acmicpc.net
🐍파이썬
import sys input=sys.stdin.readline n = int(input()) cpu = {"ADD": "0000", "SUB": "0001", "MOV":"0010", "AND":"0011", "OR":"0100", "NOT":"0101", "MULT":"0110", "LSFTL":"0111", "LSFTR":"1000", "ASFTR":"1001", "RL":"1010", "RR":"1011"} for _ in range(n): bit4 = 0 a = list(input().split()) if a[0][-1] == "C": #마지막 알파벳이 C인 경우 비트4가 1 print(cpu[a[0][:-1]], end="") print("1", end="") bit4 = 1 #비트4가 1 else: print(cpu[a[0]], end="") print("0", end="") print("0", end="") #비트5, 항상 0 print(bin(int(a[1]))[2:].zfill(3), end="") #비트6~8, rD print(bin(int(a[2]))[2:].zfill(3), end="") #비트9~11, rA if bit4 == 0: #rB, 12~14, 비트15=0 print(bin(int(a[3]))[2:].zfill(3), end="") print("0") else: ##C, 12~15 print(bin(int(a[3]))[2:].zfill(4))
💡 숫자 자리수 맞추기(zfill, rjust, ljust)
"13".zfill(5) # 00013 -> 5자리수, 왼쪽 패딩 "6".rjust(5, "0") # 00006 -> 5자리수, 왼쪽 패딩 "7".ljust(5, "0") # 70000 -> 5자리수, 오른쪽 패딩
다른 풀이 방법
import sys iterations = int(sys.stdin.readline()) opcodes = ['ADD', 'ADDC', 'SUB', 'SUBC', 'MOV', 'MOVC', 'AND', 'ANDC', 'OR', 'ORC', 'NOT', 'DUMMY', 'MULT', 'MULTC', 'LSFTL', 'LSFTLC', 'LSFTR', 'LSFTRC', 'ASFTR', 'ASFTRC', 'RL', 'RLC', 'RR', 'RRC' ] for i in range(iterations): mc = 0 opcode, rD, rA, rB = sys.stdin.readline().split() code = opcodes.index(opcode) mc += code * 2**11 mc += int(rD) * 2**7 mc += int(rA) * 2**4 mc += int(rB) * 2**(1-code%2) print(bin(mc)[2:].zfill(16))
반응형
'Problem Solving > 백준' 카테고리의 다른 글
[백준|파이썬] 2852: NBA 농구 (실버3) (0) | 2023.06.27 |
---|---|
[백준|파이썬] 1138: 한 줄로 서기 (실버2) (0) | 2023.06.24 |
[백준|파이썬] 3568: iSharp (실버5) (0) | 2023.05.05 |
[백준|파이썬] 14719: 빗물 (골드5) (0) | 2023.05.04 |
[백준|파이썬] 7568: 덩치 (실버5) (2) | 2023.04.30 |
[백준|파이썬] 4673: 셀프 넘버 (실버5) (0) | 2023.04.29 |