[리트코드] Easy|620. Not Boring Movies; MOD, 비트연산자&, 나머지연산자%
https://leetcode.com/problems/not-boring-movies/description/
1. Problem
조건에 맞는 영화 목록을 추출해야 한다.
- 조건 1: ID가 홀수(odd-numbered)일 것.
- 조건 2: 설명(description)이 'boring'이 아닐 것.
- 정렬: 평점(rating)이 높은 순서대로 내림차순 정렬.
2. Solution: 세 가지 색깔의 홀수 판별법
① 나머지 연산자 (%) 활용 가장 직관적이며 많은 프로그래밍 언어에서 공통적으로 쓰이는 방식입니다.
② MOD 함수 활용 표준 SQL 함수를 사용하여 가독성을 높인 방식입니다.
③ 비트 연산자 (&) 활용 (심화) 숫자를 2진수로 변환하여 마지막 비트가 1인지를 체크하는 가장 '컴퓨터 친화적'인 방식입니다.
3. Takeaway: 방식별 객관적 특징 비교
- 왜 비트 연산인가?: 홀수를 2진수로 표현하면 1(0001), 3(0011), 5(0101)와 같이 마지막 자리가 항상 1입니다. id & 1은 마지막 비트가 1인지만 검사하므로, 나눗셈 연산을 수행하는 %나 MOD보다 CPU 부하가 적어 성능 최적화에 유리합니다.
- 주의사항: description != 'boring' 조건을 빠뜨리지 않도록 주의해야 합니다. 데이터가 문자열일 경우 대소문자 구분 여부도 환경에 따라 체크가 필요합니다.
Table: Cinema
+----------------+----------+
| Column Name | Type |
+----------------+----------+
| id | int |
| movie | varchar |
| description | varchar |
| rating | float |
+----------------+----------+
id is the primary key (column with unique values) for this table.
Each row contains information about the name of a movie, its genre, and its rating.
rating is a 2 decimal places float in the range [0, 10]
Write a solution to report the movies with an odd-numbered ID and a description that is not "boring".
Return the result table ordered by rating in descending order.
The result format is in the following example.
Example 1:
Input:
Cinema table:
+----+------------+-------------+--------+
| id | movie | description | rating |
+----+------------+-------------+--------+
| 1 | War | great 3D | 8.9 |
| 2 | Science | fiction | 8.5 |
| 3 | irish | boring | 6.2 |
| 4 | Ice song | Fantacy | 8.6 |
| 5 | House card | Interesting | 9.1 |
+----+------------+-------------+--------+
Output:
+----+------------+-------------+--------+
| id | movie | description | rating |
+----+------------+-------------+--------+
| 5 | House card | Interesting | 9.1 |
| 1 | War | great 3D | 8.9 |
+----+------------+-------------+--------+
Explanation:
We have three movies with odd-numbered IDs: 1, 3, and 5. The movie with ID = 3 is boring so we do not include it in the answer.
1. 나머지 연산자(%)를 이용한 풀이
-- 홀수 ID인 데이터만 가져오기
SELECT *
FROM MyNumbers
WHERE num % 2 = 1 AND description != 'boring'
ORDER BY rating DESC;
2. MOD 함수를 이용한 풀이
# 나머지 함수 MOD(분자,분모)
SELECT *
FROM Cinema
WHERE MOD(id,2) = 1 AND description != 'boring'
ORDER BY rating DESC;
3. 비트연산자(&)를 이용한 풀이
# 비트 연산: 홀수는 2진수로 나타냈을 때 마지막 자리가 항상 1
SELECT *
FROM MyNumbers
WHERE (num & 1) = 1 AND description != 'boring' # num & 1: 마지막 비트가 1인지 확인
ORDER BY rating DESC;