https://programmers.co.kr/learn/courses/30/lessons/77885
✅ Solution
- 숫자가 짝수인 경우, 항상 가장 마지막 비트는 0이다. 따라서 마지막 비트를 0에서 1로 바꿔준 값이 답이기 때문에 숫자+1 값을 answer에 넣어준다.
- 숫자가 홀수인 경우,
- 가장 뒤쪽에 있는 0을 1로 바꿔주고 그다음 비트를 0으로 바꿔주면 된다.
- 예를 들어 7(0111) 은 가장 뒤쪽에 있는 0을 1로 바꿔주고 그다음 비트를 0으로 바꿔준다. 즉, 11(1011)이 답이다.
- 그리고 9(1001) 은 1001 -> 1011 -> 1010 으로 10이 답이다.
✅ Code
def solution(numbers):
answer = []
for number in numbers:
if number % 2 == 0:
answer.append(number + 1)
continue
number_bin = '0' + bin(number)[2:]
number_bin = number_bin[:number_bin.rindex('0')] + '10' + number_bin[number_bin.rindex('0') + 2:]
answer.append(int(number_bin, 2))
return answer
'코딩테스트 > 프로그래머스' 카테고리의 다른 글
[프로그래머스] Level 2 - 전력망을 둘로 나누기 (Python) (1) | 2022.06.24 |
---|---|
[프로그래머스] Level 2 - 피로도 (Python) (0) | 2022.06.23 |
[프로그래머스] Level 2 - 다리를 지나는 트럭 (Python) (0) | 2022.06.22 |
[프로그래머스] Level 2 - 위장 (Python) (0) | 2022.06.09 |
[프로그래머스] Level 2 - 게임 맵 최단거리 (Python) (0) | 2022.06.09 |