입력으로 십진수가 주어지면 작업은 주어진 십진수를 동등한 이진수로 변환하는 Python 프로그램을 작성하는 것입니다.
예:
Input : 7 Output :111 Input :10 Output :1010>
방법 #1: 재귀적 솔루션
DecimalToBinary(num): if num>= 1: DecimalToBinary(num // 2) 인쇄 num % 2>

다음은 위의 재귀 솔루션을 구현한 것입니다.
파이썬3
# Function to convert decimal number> # to binary using recursion> def> DecimalToBinary(num):> > >if> num>>=> 1>:> >DecimalToBinary(num>/>/> 2>)> >print>(num>%> 2>, end>=> '')> # Driver Code> if> __name__>=>=> '__main__'>:> > ># decimal value> >dec_val>=> 24> > ># Calling function> >DecimalToBinary(dec_val)> |
>
>
json 파일을 여는 방법산출
011000>
방법 #2: 내장 함수를 사용하여 10진수를 2진수로 변환
파이썬3
# Python program to convert decimal to binary> > # Function to convert Decimal number> # to Binary number> def> decimalToBinary(n):> >return> bin>(n).replace(>'0b'>, '')> > # Driver code> if> __name__>=>=> '__main__'>:> >print>(decimalToBinary(>8>))> >print>(decimalToBinary(>18>))> >print>(decimalToBinary(>7>))> |
>
>산출
1000 10010 111>
방법 #3: 내장 기능 없음
파이썬3
# Python program to convert decimal to binary> > # Function to convert Decimal number> # to Binary number> def> decimalToBinary(n):> >return> '{0:b}'>.>format>(>int>(n))> > # Driver code> if> __name__>=>=> '__main__'>:> >print>(decimalToBinary(>8>))> >print>(decimalToBinary(>18>))> >print>(decimalToBinary(>7>))> |
크롬 주소 표시줄
>
>산출
1000 10010 111>
빠른 닌자 방법: 사용자 입력을 사용하여 10진수를 2진수로 변환하는 한 줄 코드
파이썬3
# Quick Ninja One line Code> print>(>bin>(>4785>)[>2>:])> |
>
>산출
1001010110001>
또는
파이썬3
# Use this for user input> #decNum = int(input('Enter any Decimal Number: '))> decNum>=> 4785> print>(>bin>(decNum)[>2>:])> decNum1>=> 10> print>(>bin>(decNum1)[>2>:])> decNum2>=> 345> print>(>bin>(decNum2)[>2>:])> |
>
>산출
1001010110001 1010 101011001>
비트 시프트 연산자>>를 사용합니다.
파이썬3
def> dec2bin(number:>int>):> >ans>=> ''> >if> ( number>=>=> 0> ):> >return> 0> >while> ( number ):> >ans>+>=> str>(number&>1>)> >number>=> number>>>1> > >ans>=> ans[::>->1>]> >return> ans> def> main():> >number>=> 60> >print>(f>'The binary of the number {number} is {dec2bin(number)}'>)> # driver code> if> __name__>=>=> '__main__'>:> >main()> |
>
>산출
The binary of the number 60 is 111100>
내장 형식 방법 사용:
내장된 format() 함수를 사용하는 또 다른 접근 방식입니다. 이 접근 방식에는 10진수를 정수로 변환한 다음 'b' 형식 지정자와 함께 format() 함수를 사용하여 이를 이진 문자열로 변환하는 작업이 포함됩니다. 그런 다음 나중에 사용하기 위해 이진 문자열을 인쇄하거나 저장할 수 있습니다.
다음은 이 접근 방식을 사용하는 방법에 대한 예입니다.
파이썬
자바에서 문자열의 동등성
def> decimal_to_binary(decimal_num):> >binary_str>=> format>(>int>(decimal_num),>'b'>)> >return> binary_str> print>(decimal_to_binary(>7>))># prints 111> print>(decimal_to_binary(>10>))># prints 1010> #This code is contributed by Edula Vinay Kumar Reddy> |
>
>산출
111 1010>