반응형


파이썬은 진법변환 프로그램을 슬라이싱을 통해 아주 쉽게 만들 수 있다.


우선 n을 입력받고 n % 2의 나머지가 0이면 '0'을 ans에 추가, 그게 아니면 '1'을 추가해주고


마지막으로 n == 1일때 ans에 '1'을 추가해서


ans[::-1]을 리턴해주면 간단하게 2진수의 결과를 볼 수 있게된다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
def DtoB(n):
    if n == 1:
        return '1'
    ans = ''
    while True:
        if n % == 0:
            ans+='0'
        else:
            ans+='1'
        n = n / 2
 
        if n==1:
            ans+='1'
            return ans[::-1]
 
= int(raw_input())
 
print DtoB(n)
  
//                                                       This source code Copyright belongs to Crocus
//                                                        If you want to see more? click here >>
Crocus

    















반응형