-- 예전 기록/BOJ

[ BOJ ] 24578 : Ultimate Binary Watch ( BRONZE 2 ) / C, Python

rejo 2023. 11. 21. 10:50

문제

The Ultimate Binary Watch is a maker project that uses small LEDs to display time on a watch face. The display uses four columns of four LEDs each, with each column representing one digit of the current time in hours and minutes. Time is displayed in 24-hour format, with the 1st (left-most) column displaying the tens position for hours, the 2nd column displaying the ones position for hours, the 3rd column displaying the tens position for minutes, and the last (right-most) column displaying the ones position for minutes. The bottom LED of each column shows the lowest-order bit of its represented digit, with the bit positions increasing moving up the column. For example, the time 1615 would be displayed as shown in the figure.

Write a program that will take a 24-hour time and print the corresponding watch face.

입력

The input has a single line with 4 digits describing a valid 24-hour time between 0000 and 2359.

출력

Output four lines with a representation of the watch face displaying the given time. The tens of hours shall be in the 1st column, the single hours in the 3rd, the tens of minutes in the 7th, and the single minutes in the 9th. Use asterisks to represent bits that are set and periods to represent bits that are clear. Columns not used are to be filled with spaces. No extra whitespace are to appear at the beginning or end of any output line.

풀이 과정

4자리 숫자를 한 열에 하나씩 2진수를 표현하는 것처럼 0을 . 로, 1을 *로 출력한다.

비트 Shift 연산을 이용하면 한 자리당 하나씩 표기법을 판단할 수 있다.

 

1을 i 자리 만큼 왼쪽으로 Shift 한 것과 수를 AND 연산 하여 i 번째 자리에 1 비트가 있는지 확인했고, 있으면 *, 없으면 . 을 출력했다. 그 외의 출력 방법에 유의하며 문제를 풀이하자.

C

#include <stdio.h>

int main(void) {
    char digits[5];
    scanf("%s", digits);

    for (int i = 3; i >= 0; i--) {
        for (int j = 0; j < 4; j++) {
            if (j == 1 || j == 3) printf(" ");
            else if (j == 2) printf("   ");
            if (((digits[j] - '0') & (1 << i)) >> i) printf("*");
            else printf(".");
        }
        printf("\n");
    }
    return 0;
}

Python

import sys
input = sys.stdin.readline

digits = input().rstrip()

for i in range(4):
    for j in range(4):
        print('*' if ((int(digits[j])) & (1 << (3-i))) >> (3-i) else '.', end='')
        if j == 1: print('   ', end='')
        elif j != 3: print(' ', end='')
    print()