일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- type assertion
- linux 배포판
- prettier-plugin-tailwindcss
- helm-chart
- TypeScript
- docker
- Custom Hook
- 회고
- 클라이언트 상태 관리 라이브러리
- 프로세스
- 암묵적 타입 변환
- Sparkplug
- Recoil
- useLayoutEffect
- AJIT
- CS
- Compound Component
- react
- Headless 컴포넌트
- jotai
- JavaScript
- Render Queue
- 타입 단언
- task queue
- Redux Toolkit
- Microtask Queue
- zustand
- 좋은 PR
- 명시적 타입 변환
- 주니어개발자
Archives
- Today
- Total
구리
[Algorithm] 프로그래머스 - 다음 큰 숫자 (Java) 본문
[문제]
https://programmers.co.kr/learn/courses/30/lessons/12911?language=java
[나의 풀이]
class Solution {
public int solution(int n) {
int answer = 0;
String binaryN = Integer.toBinaryString(n);
int next = n;
while(true){
String binaryNextN = Integer.toBinaryString(++next);
if(countChar(binaryN,'1') == countChar(binaryNextN,'1')){
answer = next;
break;
}
}
return answer;
}
public static int countChar(String str,char ch){
return str.length() - str.replace(String.valueOf(ch),"").length();
}
}
1) 제시된 매개변수 n을 2진수로 변환 (binaryN)
2) n을 1씩 증가시킨 후 2진수로 변환 (binaryNextN)
3) binaryN과 binaryNextN 두 문자열에서 1의 갯수를 반환하는 함수 countChar()를 사용하여 1의 갯수가 같은지 비교
4) 1의 갯수가 같다면 while 반복문 break
하는 방식으로 문제를 풀었지만 효율성 테스트에서 시간 초과로 통과하지 못했다.
[향상된 나의 풀이]
class Solution {
public int solution(int n) {
int bitCount = Integer.bitCount(n);
while(true){
if(bitCount == Integer.bitCount(++n)){
break;
}
}
return n;
}
}
Integer 클래스에 내장된 메소드 중 bitCount(int i) 라는 숫자 데이터의 비트데이터(2진데이터이며 binary데이터) 중 1 비트의 수를 카운트해주는 메소드를 이용하여 더 간결하게 작성하여 효율성 테스트도 통과하였다.
'혼자 공부,정리하는 알고리즘' 카테고리의 다른 글
[Algorithm] 프로그래머스 - 문자열 압축 (Java) (0) | 2021.10.26 |
---|---|
[Algorithm] 프로그래머스 - 타겟 넘버 (0) | 2021.10.20 |
[Algorithm] 프로그래머스 이상한 문자 만들기 (Java) (0) | 2021.10.12 |
[Algorithm] 최대공약수, 최소공배수 (0) | 2021.10.04 |
[Algorithm] 백준 10989. 수 정렬하기 3 (Java) (0) | 2021.10.02 |