(Java)프로그래머스 - 점프와 순간 이동

윤준혁·2024년 4월 1일

나의 풀이

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

        while (true) {
            if (n % 2 == 0) { // 1
                n /= 2;
            } else { // 2
                n--;
                ans++;
            }
            
            if (n == 0) break;
        }

        return ans;
    }
}

과정

거꾸로 탐색하는게 맞다고 생각했다
1. n이 짝수이면 n / 2 해주고
2. n이 홀수이면 n - 1 해주고, ans + 1 해준다

다른 사람 풀이

public class Solution {
    public int solution(int n) {
        int sub = 1;
        int ans = 0;
        while(n != 0){
            if(n % 2 == 1){
                n -= sub;
                ans += 1;
            }
            n /= 2;
        }
        return ans;
    }

}

0개의 댓글