Programmers 2개 이하로 다른 비트
Question
https://school.programmers.co.kr/learn/courses/30/lessons/77885
First try
I did just like the question example where I incremented each number by 1 and counted bit difference. This worked for most except 2 test cases which I assume is a very long list and thus caused runtime error.
Improvement
I googled and there is a pattern.
https://velog.io/@sem/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4-LEVEL2-2%EA%B0%9C-%EC%9D%B4%ED%95%98%EB%A1%9C-%EB%8B%A4%EB%A5%B8-%EB%B9%84%ED%8A%B8-Python
Firstly for even numbers, adding value 1 (the next odd number) is already the answer cuz even numbers look like 110 or 100 so adding 1 will just increase the least significant bit.
However, for odd numbers, this is when we need to find a pattern. Actually, we just need to find the rightmost 0 and all the leftmost bits to that 0 do not matter. If we change that rightmost 0 to 1, we know that new number has a bit difference of less than 3 for sure. But we cannot guarantee that it would be the smallest number. So we need to change the 1 to the right of the rightmost 0 as 0 to ensure it is smallest.
You can do via converting to binary via bin() and converting back to int(,2) or you can do really a pure 100% bit like in that link.
def solution(numbers):
answer=[]
for num in numbers:
if num%2==0:
answer.append(num+1)
else:
# slice cuz bin() makes it 0b blabla so want to remove 0b
y='0'+bin(num)[2:]
index = y.rfind('0')
y=list(y)
y[index]='1'
y[index+1]='0'
answer.append(int(''.join(y),2))
return answer