- 난이도: Lv2
프로그래머스 링크: https://school.programmers.co.kr/learn/courses/30/lessons/12980
풀이 링크(GitHub): hayannn/CodingTest_Java/프로그래머스/2/점프와 순간 이동
풀이 시간 : 12분
import java.util.*;
public class Solution {
public int solution(int n) {
int answer = 0;
while (n > 0) {
if (n % 2 == 0) {
n /= 2;
} else {
n--;
answer++;
}
}
return answer;
}
}
O(logN)
으로 기존 방식과 동일하나, 코드 줄을 많이 줄일 수 있다는 점에서 좋은 코드라고 생각.import java.util.*;
public class Solution {
public int solution(int n) {
return Integer.toBinaryString(n).replace("0", "").length();
}
}