문제 설명
양의 정수 n이 주어질 때, n보다 작거나 같은 양의 정수 중 가장 큰 "세제곱 수"를 출력하는 프로그램을 작성하세요.
여기서 "세제곱 수"란, 어떤 정수의 세제곱인 수를 말합니다.
입력 형식
· n : 양의 정수
출력 형식
· n 이하인 세제곱 수를 정수로 반환
제약 사항
· 1 <= n <= 100000000
입출력 예시
· 예시1
· 입력
· n = 15
· 출력 : 8
· 설명 : 8은 2의 세제곱 수이다.
· 예시2
· 입력
· n = 99
· 출력 : 64
· 설명 : 64는 4의 세제곱 수이다.
작성 코드
public class Solution223 {
public int solution(int n) {
int result;
int answer = 0;
for (int i = 1; i <= n; i++) {
result = i * i * i;
if (result <= n) {
answer = result;
} else {
break;
}
}
return answer;
}
public static void main(String[] args) {
Solution223 st = new Solution223();
int n = 15;
System.out.println(st.solution(n));
int n2 = 99;
System.out.println(st.solution(n2));
int n3 = 2000;
System.out.println(st.solution(n3));
}
}
정답 코드
class Solution {
public int solution(int n) {
int lastPow = 0;
for (int i = 0; i < 1000; i++) {
int currPow = i*i*i;
if (currPow > n) {
break;
}
lastPow = currPow;
}
return lastPow;
}
public static void main(String[] args) {
Solution st = new Solution();
int n = 15;
System.out.println(st.solution(n));
int n2 = 99;
System.out.println(st.solution(n2));
int n3 = 2000;
System.out.println(st.solution(n3));
}
}
'연습 코딩테스트' 카테고리의 다른 글
연습문제 2-2(5) 정수 자릿수를 거꾸로 뒤집기 (0) | 2023.04.06 |
---|---|
연습문제 2-2(4) 술래가 빼간 구슬의 번호 (0) | 2023.04.06 |
연습문제 2-2(2) 정수 배열 요소 반복(홀수 1회) shift (0) | 2023.04.06 |
연습문제 2-2(1) 전체 사용한 전기 요금 (0) | 2023.04.05 |
연습문제 2-1(5) 두 배열에 모두 존재하는 숫자 (0) | 2023.04.05 |