코딩,해볼까

07.24. 프로그래머스 : 이진수 더하기 본문

Back/TIL

07.24. 프로그래머스 : 이진수 더하기

떠굥 2023. 7. 24. 07:53

 

문제 링크

1. 나의 풀이

def solution(bin1, bin2):
    answer = ''
    round_up = 0
    bin_plus = int(bin1)+int(bin2) # 숫자 21
    bin_list = list(str(bin_plus))
    bin_list.reverse()
    
    for i in range(len(str(bin_plus))):
        bin_i = bin_list[i] # 문자 2, 1
        print(bin_i, round_up)
        bin_num = int(bin_i) + round_up
        print("결과", bin_num)
        round_up = 0

        if bin_num == 0:
            answer += '0'
        elif bin_num == 1:
            answer += '1'
        elif bin_num == 2:
            answer += '0'
            round_up = 1
        elif bin_num == 3:
            answer += '1'
            round_up = 1
            
    if round_up == 1:
        answer += '1'

    return answer[::-1]

 

2. 풀이과정

    answer = ''
    round_up = 0
    binary = str(int(bin1) + int(bin2))[::-1] #21
    
    for i in binary:

        plus_i = str(int(i) + round_up)
        round_up = 0
        if plus_i == '0':
            answer += '0' 
        elif plus_i == '1':
            answer += '1' 
        elif plus_i == '2':
            answer += '0' 
            round_up += 1
        elif plus_i == '3':                      
            answer += '1' 
            round_up += 1
        
    if round_up == 1:
        answer += '1' 
            
    return answer[::-1]
def solution(bin1, bin2):
    # 2진수 > 10진수 연산 > 2진수
    bin_plus = int(bin1, 2) + int(bin2,2) #10진수로 만들기 성공
    # TypeError: int() can't convert non-string with explicit base 진수들은 str
    # print(int('101', 2))
    return bin(bin_plus)[2:]
Comments