본문 바로가기
코딩테스트/Python

[python 백준 16953] A->B

by nahkim 2023. 4. 12.

 

📜 접근 방법

역으로 B에서 시작해서 A를 만들수 있는지 확인하는 방식으로 짰다.

 

 

❌ 실패 코드

45%정도에서 틀렸다고 했는데 else 부분에선 맨 뒤에 숫자가 1 뿐만아니라 홀수인 수들이 다 들어가서 나는 오류였다.

s, e = map(int, input().split())
cnt = 1

while s < e:
    if e % 2 == 0:
        e //= 2
    else:
        e //= 10
    cnt += 1

if s == e:
    print(cnt)
else:
    print(-1)

 

✅ 정답 코드

s, e = map(int, input().split())
cnt = 1

while s < e:
    if e % 2 == 0:
        e /= 2
        cnt += 1
    elif e % 10 == 1:
        e //= 10
        cnt += 1
    else:
        break

if s == e:
    print(cnt)
else:
    print(-1)

 

💡알게 된점

if, else 사용시 else에 들어가면 안될 것이 들어가는지 잘 확인하자!