Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

21.05.13 - [PG - 월간 코딩 챌린지 시즌 2] 2개 이하로 다른 비트 #67

Closed
suhyunsim opened this issue May 15, 2021 · 0 comments
Assignees
Labels
lv.2 프로그래머스 - level 2 실패 시도했지만 맞지 못한 문제

Comments

@suhyunsim
Copy link
Owner

문제

핵심 아이디어

스크린샷, 2021-05-15 23-08-51

  • 우선 마지막 자리(2^0)가 0인 경우 1만 더해준 숫자가 답이 된다.
  • 1인 경우 이진수 중에 0이 있는 곳을 찾아서 변경해주고 해당 숫자를 찾는다
  • 1인 경우 0이 있는 곳이 없다면(모두 1인 경우) 제일 앞 자리 수만 바꿔주기

어려운 점, 실수

  • 직접 해당 숫자보다 큰 수들을 하나씩 이진법으로 변경해보면서 2개 이하인 것들을 찾으려고 했다. -> 런타임에러 등 통과하지 못하는 테스트들이 있었음
  • 간단히 생각해서 모든 자리가 아니라 부분적으로 확인해보면 풀 수 있었을듯

풀이

package main.java.com.poogle.PG.Q77885;

import java.util.Arrays;

public class Solution {
    public static void main(String[] args) {
        long[] ans = solution(new long[]{2, 7});
        System.out.println(Arrays.toString(ans));
    }

    public static long[] solution(long[] numbers) {
        long[] answer = new long[numbers.length];
        for (int i = 0; i < numbers.length; i++) {
            answer[i] = findClosest(numbers[i]);
        }
        return answer;
    }

    private static long findClosest(long number) {
        String origin = Long.toBinaryString(number);
        if (origin.charAt(origin.length() - 1) == '0') {
            return number + 1;
        } else {
            int i = 0;
            for (i = origin.length() - 1; i >= 0; i--) {
                if (origin.charAt(i) == '0') {
                    break;
                }
            }
            String next;
            if (i == -1) {
                //모두 1인 경우
                next = "10" + origin.substring(1);
            } else {
                //0이 하나라도 있는 경우
                next = origin.substring(0, i) + "10" + origin.substring(i + 2);
            }
            return Long.parseLong(next, 2);
        }
    }
}
@suhyunsim suhyunsim added 실패 시도했지만 맞지 못한 문제 lv.2 프로그래머스 - level 2 labels May 15, 2021
@suhyunsim suhyunsim added this to the 5월 2주 차 milestone May 15, 2021
@suhyunsim suhyunsim self-assigned this May 15, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
lv.2 프로그래머스 - level 2 실패 시도했지만 맞지 못한 문제
Projects
None yet
Development

No branches or pull requests

1 participant