λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
πŸ’κ³΅λΆ€/μ•Œκ³ λ¦¬μ¦˜

[ν”„λ‘œκ·Έλž˜λ¨ΈμŠ€ Lv.2] λ‹€μŒ 큰 숫자

by rindev 2020. 12. 5.

programmers.co.kr/learn/courses/30/lessons/12911

 

μ½”λ”©ν…ŒμŠ€νŠΈ μ—°μŠ΅ - λ‹€μŒ 큰 숫자

μžμ—°μˆ˜ n이 μ£Όμ–΄μ‘Œμ„ λ•Œ, n의 λ‹€μŒ 큰 μˆ«μžλŠ” λ‹€μŒκ³Ό 같이 μ •μ˜ ν•©λ‹ˆλ‹€. 쑰건 1. n의 λ‹€μŒ 큰 μˆ«μžλŠ” n보닀 큰 μžμ—°μˆ˜ μž…λ‹ˆλ‹€. 쑰건 2. n의 λ‹€μŒ 큰 μˆ«μžμ™€ n은 2μ§„μˆ˜λ‘œ λ³€ν™˜ν–ˆμ„ λ•Œ 1의 κ°―μˆ˜κ°€ κ°™μŠ΅λ‹ˆ

programmers.co.kr

 

 

λ‚˜μ˜ 문제점! bin() 을 μ•ˆμΌλ‹€!!!!!!!!!!!!!!!!!!!!!!!!!!!!! κ·Έλž˜μ„œ!!!!!!!!!!!!! μ΄μ§„μˆ˜λ₯Ό ν•˜λ‚˜μ”© λ‹€ λ§Œλ“€μ–΄μ€¬λ‹€ λ©μ²­ν•˜λ©΄ λͺΈμ΄ κ³ μƒν•œλ‹€λ”λ‹ˆ..

 

πŸ’ μ€‘μš”ν•œ 사싀

  • bin(n) : 2μ§„μˆ˜λ‘œ λ§Œλ“€μ–΄μ€Œ. return type = str
  • hex(n) : 16μ§„μˆ˜λ‘œ λ§Œλ“€μ–΄μ€Œ. return type = str
  • oct(n) : 8μ§„μˆ˜λ‘œ λ§Œλ“€μ–΄μ€Œ. return type = str
  • int(x, y) : x = λ³€κ²½ν•˜λ €λŠ” 숫자, y = λ³€κ²½ν•˜λ €λŠ” 숫자의 μ§„μˆ˜
    • int("0b1011", 2) = 2μ§„μˆ˜ 1011을 10μ§„μˆ˜λ‘œ λ°”κΎΈκ² λ‹€ = κ²°κ³Όκ°’ : 11

 

πŸƒ‍♀️ μž‘μ„±ν•œ μ½”λ“œ (bin μ“°μ§€μ•Šκ³  2μ§„μˆ˜λ‘œ λ°”κΏˆ)

더보기

 

def solution(n):
    answer = 0
    
    def convert_bin(n):
        n_binary = ''
        while n > 0:
            n_binary += str(n%2)
            n = n // 2
        n_binary = n_binary[::-1] #μ—­μ •λ ¬
        return n_binary

    bin_n = convert_bin(n)
    cnt = bin_n.count('1') #n을 2μ§„μˆ˜λ‘œ λ³€ν™˜ν•œ κ²ƒμ—μ„œ 1의 갯수

    while 1:
        n += 1 #숫자λ₯Ό 1μ”© 올림
        tmp_cnt = convert_bin(n).count('1')
        
        if cnt == tmp_cnt : #1의 κ°―μˆ˜κ°€ κ°™μœΌλ©΄
            answer = n
            break
    
    return answer

 

 

πŸƒ‍♀️ 더 멋진 μ½”λ“œ (bin(n) μ‚¬μš©)

더보기

 

def solution(n):
    answer = 0
    
    n_cnt = bin(n).count('1')
    
    while 1:
        n += 1
        tmp_cnt = bin(n).count('1')
        if tmp_cnt == n_cnt:
            answer = n
            break
    
    return answer

 

 

λŒ“κΈ€