Algorithm/Code Signal
centuryFromYear
마산와사비
2023. 3. 10. 02:03
문제
- https://app.codesignal.com/arcade/intro/level-1/egbueTZRRL5Mm4TXN
- Given a year, return the century it is in. The first century spans from the year 1 up to and including the year 100, the second - from the year 101 up to and including the year 200, etc.
- Example
- For year = 1905, the output should be solution(year) = 20;
- For year = 1700, the output should be solution(year) = 17.
Input/Output
- [execution time limit] 3 seconds (java)
- [input] integer year
- Guaranteed constraints:
1 ≤ year ≤ 2005. - A positive integer, designating the year.
- Guaranteed constraints:
- [output] integer
- The number of the century the year is in.
풀이
int solution(int year) {
return (int) Math.ceil((double)year/100);
}
Note
- Java.Lang package의 Math 클래스를 이용하여 쉽게 풀 수 있을 줄 알았으나, 기본 개념 확인이 필요한 문제
- Math.ceil의 경우, return 형이 double이지만 문제의 return 형은 int
- int로 강제형 변환하는 경우, 소수점을 삭제
- 따라서, 내림 처리가 필요한 경우 int로 강제형 변환을 사용할 수 있음
- 해당 문제의 경우 올림이 필요한 케이스이므로 double형으로 변환하여 계산 후, 이 결과값을 int로 변환하여 올림한 값을 리턴할 수 있도록 처리
- Java에서 올림을 처리할 수 있는 다양한 방법은 아래 링크 참고