-
[프로그래머스] [JAVA] [Level 2] [연습문제] 다음 큰 숫자PROGRAMMERS/연습문제 2022. 9. 15. 23:12
1. Integer.toBinaryString() + replace() + length()
import java.util.*; class Solution { public int solution(int n) { int answer = 0; while(true){ answer++; if(answer>n && Integer.toBinaryString(answer).replace("0","").length() == Integer.toBinaryString(n).replace("0","").length()){ return answer; } } } }
- 테스트 케이스는 통과하지만 효율성 테스트에서 시간 초과됨
2. for문으로 조건1을 만족 + Integer.bitCount
import java.util.*; class Solution { public int solution(int n) { int answer = 0; // n보다 1크게 설정해줌으로써 조건 1만족 for(int i=n+1; ; i++){ // i의 이진수중 true의 개수와 n의 이진수중 true의 개수가 같을 때 if(Integer.bitCount(i) == Integer.bitCount(n)){ answer = i; return answer; } } } }
- 통과
- Integer.toBinaryString(n) - 10진수 -> 2진수
- Integer.bitCount(n) - 정수 n에서 true bit의 개수 반환
'PROGRAMMERS > 연습문제' 카테고리의 다른 글
[프로그래머스] [JAVA] [Level 2] [연습문제] 멀리 뛰기 (0) 2022.09.21 [프로그래머스] [JAVA] [Level 2] [연습문제] N개의 최소공배수 (1) 2022.09.20 [프로그래머스] [JAVA] [Level 2] [연습문제] 피보나치 수 (0) 2022.09.15 [프로그래머스] [JAVA] [Level 2] [연습문제] 숫자의 표현 (0) 2022.09.14 [프로그래머스] [JAVA] [Level 2] [연습문제] 최솟값 만들기 (0) 2022.09.09