πŸ’» Dev & CSiOS & Others

[Swift] Checking Even or Odd - Programmers Lv.0 (181944)

Problem: Given a natural number n, write code to output "n is even" if n is even, and "n is odd" if n is odd. https://school.programmers.co.kr/learn/courses/30/lessons/181944 Constraints: 1 ≀ n ≀ 1,000 Solution: let a = Int(readLine()!)! let resultString = a % 2 == 0 ? "\(a) is even" : "\(a) is odd" print(resultString) Ternary operator(μ‚Όν•­ μ—°μ‚°μž) μ‚¬μš©ν•΄μ„œ 문제λ₯Ό ν•΄κ²° ν•˜μ˜€μŠ΅λ‹ˆλ‹€. μž…λ ¨λœ 수λ₯Ό 2둜 λ‚˜λˆˆ λ‚˜λ¨Έμ§€κ°€ 0인지 ν™•μΈν•˜μ—¬ μ§μˆ˜μΈμ§€ 확인할 수 μžˆμŠ΅λ‹ˆλ‹€. let a = Int(readLine()!)! print(a, "is", a.isMultiple(of: 2) ? "even" : "odd") Alternatively, you can also determine even/odd status using Swift's isMultiple(of:) function as shown above. ...

June 29, 2023 Β· 1 min Β· Sobamemil