![[백준 / BOJ] 1330번 두 수 비교하기 (C++, Python) (부제 : 삼항 연산자)](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FTpLdn%2FbtrLovgZNG4%2FAGV0HOvP6JQCL46H2LdWik%2Fimg.jpg)
[백준 / BOJ] 1330번 두 수 비교하기 (C++, Python) (부제 : 삼항 연산자)◎ 자료구조와 알고리즘/백준(BOJ) 문제풀이2022. 9. 5. 18:56
반응형
링크 : https://www.acmicpc.net/problem/1330
1330번: 두 수 비교하기
두 정수 A와 B가 주어졌을 때, A와 B를 비교하는 프로그램을 작성하시오.
www.acmicpc.net
문제

문제 풀이
정석은 그냥 if-else문을 사용하면 되지만 삼항연산자를 사용해 보았다.
C++과 파이썬의 삼항 연산자 틀이 조금은 달라 따로 풀이를 첨부한다.
C++ 상세 풀이
C++ 풀이 펼쳐보기
C++에서의 삼항 연산자 규칙은 다음과 같다.
(조건식) ? [참일 때 실행] : [거짓일 때 실행]
즉 풀이는 아래와 같아진다.
((A > B) ? ">" : ((A < B) ? "<" : "=="))
A > B가 참일 때 : ">" 출력
거짓일 때 : ((A < B) ? "<" : "==")) 실행
A < B가 참일 때 : "<" 출력
거짓일 때 : "==" 출력
Python 상세 풀이
Python 풀이 펼쳐보기
파이썬에서의 삼항 연산자 규칙은 다음과 같다.
[참일 때 실행] if (조건식) else [거짓일 때 실행]
즉 풀이는 아래와 같아진다.
print(">") if A > B else print("<") if A < B else print("==")
A > B가 참일 때 : print(">") 실행
거짓일 때 : print("<") if A < B else print("==") 실행
A < B가 참일 때 : print("<") 실행
거짓일 때 : print("==") 실행
코드 전문
C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
void init() { | |
std::ios_base::sync_with_stdio(false); | |
std::cin.tie(nullptr); | |
std::cout.tie(nullptr); | |
} | |
int main() { | |
init(); | |
int A, B; | |
std::cin >> A >> B; | |
std::cout << ((A > B) ? ">" : ((A < B) ? "<" : "==")); | |
return 0; | |
} |
Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
input = sys.stdin.readline | |
if __name__ == "__main__": | |
A,B = map(int, input().split()) | |
print(">") if A > B else print("<") if A < B else print("==") |
소감
삼항 연산자에 대해 더 자세히 알아볼 수 있었던 문제다.
반응형
'◎ 자료구조와 알고리즘 > 백준(BOJ) 문제풀이' 카테고리의 다른 글
[백준 / BOJ] 2480번 주사위 세개 (C++, Python) (0) | 2022.09.13 |
---|---|
[백준 / BOJ] 2525번 오븐 시계 (C++, Python) (0) | 2022.09.13 |
[백준 / BOJ] 25083번 새싹 (C++, Python) (0) | 2022.09.04 |
[백준 / BOJ] 10172번 개 (C++, Python) (0) | 2022.09.04 |
[백준 / BOJ] 10171번 고양이 (C++, Python) (부제 : 이스케이프 시퀀스) (0) | 2022.09.04 |
@Reo :: 코드 아카이브
자기계발 블로그