본문 바로가기
프로그래머스/[프로그래머스 - JAVA] Lv.0

[프로그래머스 - JAVA] 저주의 숫자 3

by 코딩하는 흰둥이 2023. 3. 17.
반응형

그냥 숫자 세...

 


  • 내 풀이
class Solution {
    public int solution(int n) {
        int answer = 0;

        // 매개변수 만큼 반복
        for (int i = 1; i <= n; i++) {
            // +1 씩 올라감
            answer += 1;
            // 루프 조건문
            Boolean a = true;

            while (a){
                // 마을에서 쓰는 숫자에 3의 배수가 있거나 3이 들어가 있는 경우 다시 +1
                if (answer % 3 == 0 || String.valueOf(answer).contains("3")){
                    answer += 1;
                }else {
                    // 조건이 없으면 반복문 종료
                    a = false;
                }
            }
        }
        return answer;
    }
}

반복문 안에서 조건이 없을 때 까지 반복을 시키려다보니 시행착오를 많이 겪음

 

 

  • 다른 사람 풀이
class Solution {
    public int solution(int n) {
        int answer = 0;

        for (int i = 1; i <= n; i++) {
            answer++;
            if (answer % 3 == 0 || String.valueOf(answer).contains("3")) {
                i--;
            }
        }
        return answer;
    }
}






class Solution {
    public int solution(int n) {
        int count = 0;

        for(int i = 1; i <= n + count; i++) {
            if(i % 3 == 0 || String.valueOf(i).contains("3")) count++;
        }

        return n + count;
    }
}

댓글