알고리즘 공부/프로그래머스

(Java)프로그래머스 코딩테스트 연습 - Summer/Winter Coding(~2018) - 점프와 순간 이동

HRuler 2020. 11. 29. 16:20

1. 문제

https://programmers.co.kr/learn/courses/30/lessons/12980?language=java

 

코딩테스트 연습 - 점프와 순간 이동

OO 연구소는 한 번에 K 칸을 앞으로 점프하거나, (현재까지 온 거리) x 2 에 해당하는 위치로 순간이동을 할 수 있는 특수한 기능을 가진 아이언 슈트를 개발하여 판매하고 있습니다. 이 아이언 슈

programmers.co.kr

2. 나의 풀이

import java.util.*;

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

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

        return ans;
    }
}

3. 다른 사람 풀이

import java.util.*;

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;
    }

}