[프로그래머스 Lv.2] 다음 큰 숫자

shin·2022년 11월 23일
0

CodingTest 문제 풀이

목록 보기
70/79

[프로그래머스 Lv.2] 다음 큰 숫자

파이썬 언어 풀이

def solution(n):
    answer = 0
    num = n + 1
    count1 = 0
    for i in str(format(n, 'b')):
        if i == '1':
            count1 += 1
    while True:
        count2 = 0
        for i in str(format(num, 'b')):
            if i == '1':
                count2 += 1
        if count1 == count2:
            break
        num += 1
    return num

자바 언어 풀이

첫 번째 도전

  • 정확성 70점 + 효율성 0점 = 70점
import java.lang.*;

class Solution {
    public int solution(int n) {
        int answer = n + 1;
        int count1 = 0;
        String str = Integer.toBinaryString(n);
        String[] arr = str.split("");
        for(int i = 0; i < arr.length; i++){
            if(arr[i].equals("1")){
                count1 += 1;
            }
        }
        
         while(true){
            int count2 = 0;
            String str2 = Integer.toBinaryString(answer);
            String[] arr2 = str2.split("");
            for(int i = 0; i < arr2.length; i++){
                if(arr2[i].equals("1")){
                    count2 += 1;
                }
            }
            if(count1 == count2){
                break;
            }
            answer += 1;
         }
        return answer;
    }
}
  • 파이썬 언어로 구현했을 때 100점을 맞았던 방식을 자바 언어로 구현하면 효율성에서 점수를 받지 못함

두 번째 도전(정답)

  • 정확성 70점 + 효율성 30점 = 100점
import java.lang.*;

class Solution {
    public int solution(int n) {
        int answer = n + 1;
        int count1 = Integer.bitCount(n);
        
         while(true){
            int count2 = Integer.bitCount(answer);
            if(count1 == count2){
                break;
            }
            answer += 1;
         }
        return answer;
    }
}
  • 첫 번째 풀이는 Integer.toBinaryString()을 이용해서 2진수로 바꾸고 split으로 String 문자열을 한글자씩 나눠서 String 배열에 넣어준 후에 해당 배열을 탐색해서 1이면 count 증가시킴
String str = Integer.toBinaryString(n);
String[] arr = str.split("");
for(int i = 0; i < arr.length; i++){
	if(arr[i].equals("1")){
		count1 += 1;
	}
}
  • 두 번째 풀이는 위 과정을 모두 생략하고 Integer.bitCount()로 바로 정수를 매개 변수로 받아서 해당 정수의 2진수 형태에 대한 1의 개수를 얻을 수 있음
int count1 = Integer.bitCount(n);
profile
Backend development

0개의 댓글