문제 설명

양의 정수 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));
    }
}