일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 29 | 30 |
Tags
- Programmers
- hook
- Nextjs React 18
- React 공식문서
- context
- React 고급 안내서
- Javascript
- React API 참고서
- react
- react hook
- 고급안내서
- React 18
- background setInterval
- Render Props
- next13 head
- getUTCDate
- Babel
- Next13
- React 18 Nextjs
- background: url
- codingtest
- React 고급안내서
- Nextjs
- background setttimeout
- React18
- notFound()
- background tab
- RTK Query
- react-helmet
- CSS
Archives
- Today
- Total
akjfal
[Programmers] 2개 이하로 다른 비트 본문
// f(x) x보다 크고 x와 비트가 1~2개 다른 수들 중에서 제일 작은 수
// 1 <= numbers.length <= 100,000
// 0 <= numbers <= 10^15
// 비트연산을 하나씩 빼서 짝수가 될때까지 빼기 -> x값 구하기
// 답 : 2 ^ (x - 1)
class Solution {
public long[] solution(long[] numbers) {
int length = numbers.length;
long[] answer = new long[length];
for(int i = 0; i < length; i++){
long num = numbers[i];
long x = 0;
if(num % 2 == 0)
x++;
while(num % 2 == 1){
num = num >> 1;
x++;
}
answer[i] = numbers[i] + (long)Math.pow(2, x-1);
}
return answer;
}
}
처음에 어떠한 경우에 3개 이상 다른 것이 생겨나는지 파악하면 쉽다.
1이 연속된 비트로 끝날 경우 발생하므로, >> 연산을 통해 1의 갯수(x)를 구하고 2^(x-1)을 해주면된다. 단 0인경우는 답이 다르게나오니 처리해줘야한다.
'알고리즘 > programmers' 카테고리의 다른 글
[Programmers] 피보나치 수 (0) | 2021.06.19 |
---|---|
[Programmers] 최댓값과 최솟값 (0) | 2021.06.19 |
[Programmers] [1차] 프렌즈4블록 (0) | 2021.06.18 |
[Programmers] 영어 끝말잇기 (0) | 2021.06.18 |
[Programmers] 배달 (0) | 2021.06.18 |
Comments