이 페이지는 코딩도장 데이터의 읽기 전용 정적 보관본입니다.

2진법으로 자연수 나타내기

2진법이란, 어떤 자연수를 0과 1로만 나타내는 것이다. 예를 들어 73은 64(2^6)+8(2^3)+1(2^0)이기 때문에 1001001으로 표현한다. 어떤 숫자를 입력받았을 때 그 숫자를 2진법으로 출력하는 프로그램을 작성하시오.

2017/08/01 18:04

P.Y.Thon

188개의 풀이가 있습니다.

Python3

꼼수(?)

print(bin( int(input()) )[2:])

재귀

def binary(d): 
    return '' if d == 0 else binary(d // 2) + str(d % 2)

반복

def binary(d):
    b = ''
    while d:
        d, r = divmod(d, 2)
        b = str(r) + b
    return b

2017/08/03 04:51

Noname

꼼수 ㅋㅋㅋ 잘배웠습니다 ㅋㅋ - 김시영, 2022/06/09 14:09
a = int(input())
b = []
while a:
    b.append(a%2)
    a = int(a/2)

b.reverse()
print(b)

2017/08/07 10:40

이건우 (ekeon)

좋은 코드 감사합니다. 그런데 마지막에 print(b)로 출력할 경우 [1, 0, 1, 0] 형태로 나와서요, b.reverse() b = [str(x) for x in b] print(''.join(b)) 코드에 한 줄 추가하여 각 숫자를 붙여서 출력하는 것이 더 좋을 것 같습니다. - 판다네밥상, 2019/01/02 20:11

Ruby

bin = ->n { n < 2 ? n.to_s : bin[n/2] + (n%2).to_s }

Test

expect( bin[0] ).to eq "0"
expect( bin[1] ).to eq "1"
expect( bin[11] ).to eq "1011"

2017/08/01 20:16

rk

    public static void main(String[] args) {
        int num = 2;
        StringBuilder sb = new StringBuilder();

        while (num > 0) {
            sb.append(num % 2);
            num /= 2;
        }

        System.out.println(sb.reverse());
    }

2로 계속 나누어 나머지는 StringBuilder에 append 후에 reverse 시켰습니다.

2017/08/29 16:58

흑돼지

n=int(input("숫자입력:"))
bin(n)

a = int(input())
b = ""
while a:
    b+=str(a%2)
    a = int(a/2)
b=b[::-1]
b

2022/08/06 01:47

김보라

user_input=input('Input hex data: ')
list=[]
a=int(user_input)
if a==1:
    list.append(str(1))
else:
    while a !=1:
        if int(a)%2==0:
            list.append(str(0))
        elif int(a)%2==1:
            list.append(str(1))
        a=a/2
        if a==1:
            list.append(str(1))
            break
list.reverse()
print(''.join(list))


2017/08/02 16:58

daehyun.jung

10진법을 2진법으로 변환하여 출력하기

코드

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>10진수에서 2진수로</title>
</head>
<body>
    <form action="<? $SERVER['PHP_SELF']?>" method="get">
        <input type="text" name="number" placeholder="변환할 수를 입력하세요">
        <input type="submit" value="확인">
    </form>
    <?php
        $number = $_GET['number'];
        $binary = sprintf("%032b",$number);
        echo ($binary);
    ?>
</body>
</html>

해설

<?php $number = $_GET['number']; $binary = sprintf("%032b",$number); echo ($binary); ?>

주요 핵심 코드는 의외로 별 거 없다. $number = $_GET['number'] 부분을 통해 사용자가 입력한 수를 '$number'라는 변수에 저장한다. 그 후 sprintf 함수를 통해 '$binary'라는 변수에 32bit 2진수를 저장한다. 그 후 echo 를 사용해 출력만 하면 된다.

2017/08/02 17:07

Bak J.H. (B.J.H)

def binary(deci_number) :

    result = 0
    n = 0

    while True :

        if deci_number > 2**n :

            if deci_number < 2**(n+1) :
                result += 10**n
                deci_number -= 2**n
                n = 0
                continue

            else :
                n += 1
                continue

        elif deci_number == 2**n :

            result += 10**n
            deci_number -= 2**n
            n = 0
            continue

        elif deci_number == 0 :
            break

    return result

2017/08/02 18:58

다크엔젤

R로 작성했습니다.


bin <- function(x) {
  result <- numeric(floor(log2(x)))+1
  di <- x
  for(i in (floor(log2(x))+1):1) {
    if(di < 2^(i-1)) {
      result[i] <- 0
    }
    else {
      result[i] <- 1
      di <- (di-2^(i-1))
      }
  }
  return(rev(result))
}

2017/08/04 09:41

임승남

package com.test;

import java.util.ArrayList;
import java.util.List;

public class decimalToBinary {

    public static void main(String[] args) {

        int decimal = 73;

        toBinary(decimal);
    }

    public static void toBinary(int dec) {

        int temp = dec;

        List<Integer> bin = new ArrayList<Integer>();

        while( temp > 1 ) {                 
            bin.add(temp%2);    
            temp = temp / 2;
        }
        bin.add(1);

        System.out.print("Decimal : " + dec + " to Binary : " );

        for ( int i = bin.size()-1; i >=0; i-- ) {
            System.out.print(bin.get(i));
        }
    }
}

2017/08/04 17:14

wonjae.lee

function convertBinary(base) {
  let ans = [], tailingZero = true;
  const solve = (base) => {
    const num = Math.floor(base / 2);
    const binary = base % 2;
    if (!tailingZero || binary !== 0) {
      ans.unshift(binary);
      tailingZero = false;
    }
    return (num === 0) ? -1 : solve(num);
  }
  solve(base);
  return ans.join('');
}

console.log(convertBinary(51712));

2017/08/07 07:47

DS

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

int main()
{
    int decimal;
    int binary;
    int i = 1;

    int sum = 0;
    scanf("%d", &decimal);
    if (decimal > 0)
    {
        while (decimal >= 1)
        {
            binary = decimal % 2;
            sum= sum+binary * i;
            decimal = decimal / 2;
            i = i * 10;
        }
        printf("%d", sum);
    }
    return 0;
}

2017/08/07 21:30

김지술

C

#include <stdio.h>
#include <stdlib.h>

#define CHAR_SIZE 8
int main()
{
    char* str= (char*)malloc(sizeof(char)*CHAR_SIZE);
    char arr[256];
    int count = 0;
    for(int i=0;i<100;i++)
        arr[i] = 0;
    printf("10jinsoo ipryuk : ");
    gets(str);
    int tmp= atoi(str);
    while(tmp != 0)
    {
        sprintf(str,"%d",tmp%2);
        strcat(arr,str);        
        tmp = tmp/2;
        count++;
    }
    for(int i=count-1;i>=0;i--)
        printf("%c",arr[i]);

    return 0;
}

2017/08/08 16:09

임꺽정

def two(x):
    result=[]
    num=x
    while 1:
        if num == 1:
            result.append(1)
            break
        result.append(num%2)
        num=num//2
    result.reverse()
    return result

a=two(100)
print(a)

2017/08/09 12:06

박영호ㅋㅋ

public class binnaryOut {
    public static void main(String[] args) {
        // casting method for args to demical, etc
        int demical = 85;

        while (demical >= 1) {
            System.out.print(demical % 2);
            demical /= 2;
        }
    }
}

2017/08/10 09:46

어머언니

C로 작성했습니다.

#include <stdio.h>

void main()
{
    int num;
    printf("10진수 숫자: ");
    scanf_s("%d", &num);
    printf("2진수 숫자: ");
    while (num >= 1) {
        printf("%d", num % 2);
        num = num / 2;
    }
}

2017/08/15 00:59

우플밍

Python으로 작성하였습니다.

val=int(input("Input Decimal Value : "))
bin=[]
while val>1:
    bin.append(val%2)
    val=val//2
bin.append(1)
bin.reverse()

for i in bin:
    print(i, end='')

2017/08/15 12:33

SeongBeom Hong

파이썬입니다.

def s556():
    n = int(input())
    s = []
    while n > 0:
        s.append(str(n % 2))
        n //= 2
    return ''.join(s[::-1])

s556()

2017/08/17 15:47

룰루랄라


def bin (num):
    n = 1
    result =[]

    while num > 1:
        if ( num // (2**n) ) >= 2:
            n += 1
            ## print("####",n)
        else:
            result.append(n)
            num = num - (2**(n))
            ## print('num = ', num, n)
            n = 1

    result.append(num)
    ans = [0] * (result[0]+1)
    ans [0] = result.pop()

    for i in result:
        ans[i] = 1
    print(ans)
    ans.reverse()
    print(ans)
    print('answer = ', ''.join( str(x) for x in ans))


bin(63)

2017/08/17 17:27

ideall

  1. 0x1 마스크 비트를 출력하고자하는 비트자리로 << 연산
  2. 입력받은 숫자와 쉬프트한 마스크 비트 & 연산 후 가장 오른쪽 비트로 >> 연산 후 출력
  3. 마스크 비트를 오른쪽으로 한비트씩 쉬프트
  4. 반복

2017/08/19 14:07

TunJi

decimal = int(input("십진 데이터 입력: "))
binary = []
while decimal:
    binary.append(decimal % 2)
    decimal = int(decimal / 2)
print(binary)

2017/08/19 19:16

윤건석 (can9165)

n=73

result=""
while (n>1):
    result+= str(n%2)
    n//=2

print(result+str(n))

가장 일반적인 2진수 구하는 방법인 10진수를 2로 계속 나눈후 나머지를 꺼꾸로 읽는 방법을 사용해봤습니다.

2017/08/20 23:09

iamm00n

//10진수를 2진수로
public static void main(String[] args) {
    int xor = 1;
    int num = new Scanner(System.in).nextInt();
    System.out.println(num);

    while(xor<num) 
        xor*=2;

    while(xor>1) 
        System.out.printf("%1d",((xor/=2)&num)>0?1:0);
}

String으로 바꾸는 작업없이 int형으로

2017/08/21 14:37

장동규

#include <stdio.h>

int main(void)
{
    int n;
    scanf("%d", &n);
    while(1)
    {
        printf("%d", n % 2);
        n /= 2;
        if (n < 2)
        {
            printf("%d", n);
            break;
        }
    }
    return 0;
}

2017/08/21 15:09

Jeong Hoon Lee

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int decimal = Integer.parseInt(br.readLine());
        int mok = 0, namuji = 0;
        Stack<Integer> namujiStack = new Stack<Integer>();
        System.out.print(decimal + "을 2진수로 변환 --> ");
        while (true) {
            mok = decimal / 2;
            namuji = decimal % 2;
            namujiStack.push(namuji);
            if (mok == 1) {
                namujiStack.push(mok);
                while (!namujiStack.isEmpty()) {
                    System.out.print(namujiStack.pop());
                }
                br.close();
                break;
            }
            decimal = mok;
        }
    }
}

2017/08/22 00:51

임주성

그냥 함수 써서 출력하면 안되나요..?

a=73
bin_su=str(bin(a))
print(bin_su[2:])


결과 : 1001001

2017/08/24 20:49

박준

def f(n1):
    arr = ''
    while n1 > 0:
        arr += str(n1%2)
        n1 = n1//2
    print(arr)

f(73)

2017/08/28 10:13

piko

// golang 1.9
package main

import "fmt"

func main() {
    var inpNum int = 73
    fmt.Println(dec2bin(inpNum))
}

// 십진수 -> 이진수 변환
func dec2bin(dec int) string {
    bin := ""
    if dec >= 1 {
        bin = fmt.Sprintf("%d", dec%2) + bin
        bin = dec2bin(dec/2) + bin
    }
    return bin
}

// ans: 1001001

2017/08/29 11:22

mohenjo

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int n, i = 0, last;
    int total = 0;


    scanf("%d", &n);
    last = n; // n에 입력 받은 값을 last에 저장하여 따로 빼놓음

    while (n >= 1) // 입력받은 10진수를 2진수 갯수만큼 total에 저장
    {
        n /= 2;
        total++; // 동적할당 하기 위해 저장
    }  


    n = last; // last에 저장한 처음 n값을 다시 돌려줌
    int* twonum = (int*)malloc(sizeof(int) * total); // 1차원 동적배열


    while (n >= 1) 
    {
        twonum[i] = n % 2; // 배열에 차례로 2진수 할당
        i++;
        n = n / 2;

        if (n < 1)
        {
            for (int j = total-1; j >= 0; j--)
            {
                printf("%d", twonum[j]); // 거꾸로 된 2진수를 거꾸로 출력
            }
        }
    }

    free(twonum); // 동적할당 해제
    return 0;
}

위에 두 풀이는 잘못된거같아 작성해 봅니다.

2017/08/29 22:16

김동진

package codingdojang;

import java.util.ArrayList; import java.util.List;

public class Bit2 { static List aList = new ArrayList<>();

public static void main(String[] args) {
    get2BitArray(73);
    make2BitString();
}

static int get2Bit(int pInt) {
    for (int i = 0; i < pInt; i++) {
        double aDouble = Math.pow(2, i);
        if (aDouble > pInt) {
            return i - 1;
        }
    }

    return 0;
}

static void get2BitArray(int pInt) {

    int i = get2Bit(pInt);
    int p = (int) Math.pow(2, i);

    if (pInt % p != 0) {
        aList.add(i);
        get2BitArray(pInt % p);
    } else {
        aList.add(i);
    }

}

static String make2BitString() {
    int rInt = 0;
    for (int i = 0; i < aList.size(); i++) {
        int aInt = aList.get(i);
        aInt = (int)Math.pow(10, aInt);
        rInt = rInt + aInt;
    }
    return rInt + "";
}

}

2017/09/01 10:23

바부

#Using Python
number = input("input:")
print(bin(int(number))[2:])

2017/09/03 14:20

Genie Kim

# python 3.6
inp = int(input("Enter decimal number: "))
# print(bin(inp)[2:])  # 내장함수 이용으로도 해결 가능 또는 이하

# dec to bin
rst = list()
while inp:
    rst.insert(0, inp % 2)
    inp = inp // 2

print("".join(map(str, rst)))  # 이진 리스트를 문자로 반환 출력

2017/09/04 14:41

mohenjo

namespace _20170910
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = Console.ReadLine();
            int a = Convert.ToInt32(s);
            string value = string.Empty;
            while(true)
            {
                int b = a % 2;
                 a = a / 2;
                value += b.ToString();
                if (a == 0)
                {
                    break;
                }
            }
            Console.WriteLine(new string(value.ToArray().Reverse().ToArray()));
        }
    }
}

2017/09/10 23:02

정주영

input_number = int(input())

def binary(k):
    return(bin(k))

print(binary(input_number))

2017/09/14 18:18

Hyun Ho Yoo

def binary(number): string = ''

for num in range(100): if pow(2,num) > number: i = num-1 string = string + '1' number = number - pow(2,num-1) print(pow(2,num)) print("1string : " + string) print('1number : ' + str(number)) print(i) break

for numbers in range(i,0,-1): print("numbers : " + str(numbers)) if pow(2,numbers) > number and number - pow(2,numbers-1) >= 0:

i = numbers-1 string = string + '1' number = number - pow(2,numbers-1) print("string : " + string) print('number : ' + str(number))

continue

else: string = string + '0' print('string : ' + string) continue

binary(int(input()))

2017/09/17 18:37

rlaxorwn12

import java.util.Scanner;

public class ChangeBinary {
    public static void main(String[] args) {
        int bin[] = new int[Byte.MAX_VALUE]; // 2진수가 저장될 배열
        int pos = 0; // 배열의 위치를 저장할 변수
        int dec;//10진수를 저장할 변수
       int mok = 0; //몫
        int nmg = 0; //나머지

        Scanner in = new Scanner(System.in);
        //10진수 입력
        System.out.print("10진수 = ");
        dec = in.nextInt();

        do {
            mok = (int)dec / 2;
            nmg = dec - mok * 2;

            ++pos; // 배열 인덱스 증가.
            bin[pos] = nmg;

            dec = mok; // mok이 0이 아니면 mok을 10진수 dec으로 전환하고 반복.
        }while(mok!=0); //mok을 0일때까지 계산

        // bin배열에 저장된 nmg을 뒤에서부터 출력.
        for(int i = pos; i > 0; i--){
            System.out.print(bin[i]);
        }
        in.close();
    }
}

2017/11/10 22:08

YEAHx4

python 2.7


def bin_no(nat):
    binary = []

    while nat > 0:
        (q, r) = divmod(nat, 2)
        nat = q
        binary.append(str(r))

    bn = "".join(reversed(binary))

    return bn

print (bin_no(73))

2017/11/24 18:59

vkospi

python

input_n = input()
bin(input_n)

2017/12/11 18:13

홍철현

def two(num, result=''):
    if num<2:
        result=str(num)+result
        return(result)
    else:
        a,b=divmod(num,2)
        result=str(b)+result
        return(two(a, result))

start=int(input('n: '))
print(two(start))

2017/12/13 14:24

빗나감

def convert(i):
    b = []
    while i>2:
        b += [i%2]
        i //= 2
    b += ([0, 1] if i == 2 else [1])
    return ''.join(str(x) for x in b)[::-1]

while __name__ == '__main__':
    print(convert(int(input('>>>'))))

기본 함수 안쓰고 해봤습니다.

파이썬 3.6.2 64

2017/12/20 02:12

Flair Sizz

number_ = int(input(":"))
print(bin(number_)[2:])

2017/12/21 16:42

june davis

파이썬 3.6

def binary(x):
    rest =[]
    while x != 0:
        rest.append(str(x%2))
        x = x // 2
    rest.reverse()
    print("\n",">>> 2진수 = " ,''.join(rest))

try:
    num = int(input(" ▶ 자연수를 입력하세요 : "))
    binary(num)
except ValueError:
    print("\n","※ 잘못된 값을 입력하였습니다.","\n")
  • 결과값
 ▶ 자연수를 입력하세요 : 73

 >>> 2진수 =  1001001

2017/12/29 22:23

justbegin

x = int(input("수를 입력하세요"))
c,t,r = 0,[],[]
while x > 0:
       while x > 2**c:
              c += 1
              continue
       while 2**c > x:
              c -= 1
              continue
       t.append(c)
       x -= 2**c
       continue
c = 0
for x in range(0, t[0]+1):
       if x in t:
              r.append(1)
       else:
              r.append(0)
print(r)

2018/01/09 19:21

김영성

n = int(input("수를 입력하시오 : "))
def jinsu(number):
    a = number
    result = []
    digit = ''
    while a//2 > 0:
        result.append(a%2)
        a = a//2
    result.append(a)
    result.reverse()
    for i in range(len(result)):
        digit += str(result[i])
    return digit
print(jinsu(n))

2018/02/04 12:39

김동하

import java.util.*;

public class Main { public static void main(String[] args) { Scanner scanf=new Scanner(System.in); String s=scanf.next();

    System.out.println(Integer.toBinaryString(Integer.parseInt(s)));

}

}```{.java}

```

2018/02/07 16:24

즈스크


a=input('입력:')
i=0
result=0
try:
    while True:
        i+=1
        result+=int(a[-i])*(2**(i-1))
except:print(result)

2018/02/09 19:27

추천은 다 읽음

a=int(input('>>>'))
result=''
while a:
    result=str(int(a%2))+result
    print(result)
    a=a//2
print(result)

2018/02/10 08:16

추천은 다 읽음

for_bin_num=int(input("이진수로 바꿀 숫자를 입력하세요\n"))

bin_num=bin(for_bin_num)

print(bin_num[2:])

2018/02/17 02:28

D B

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        List<Integer> list = new LinkedList<Integer>();
        System.out.print("2진수로 바꿀 자연수를 입력하세요 :");
        int num = scanner.nextInt();
        int divideNum = 2;

        int value1 = 0;
        int value2 = 0;

        value1 = num / divideNum;
        value2 = num % divideNum;

        list.add(value1);
        list.add(value2);
        while(list.get(0) > 1) {
            value1 = list.get(0) / divideNum;
            value2 = list.get(0) % divideNum;
            list.set(0, value1);
            list.add(1, value2);
        }

        if(list.get(0) == 0) {
            list.remove(0);
        }
        Iterator<Integer> it = list.iterator();
        while(it.hasNext()) {
            System.out.print(it.next());
        }


2018/02/23 13:29

초초보

Python 3

def dectobin(number):
    a = ''
    if number:
        while number > 1:
            a = str(number%2) + a
            number = number//2
        a = '1' + a
    else:
        a = '0'
    return int(a)
def bin(n):
    return int(str(n), 2)

2018/03/11 21:47

myyh2357

import java.util.Scanner;

public class Comp{
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);

        System.out.println("숫자를 입력하세요.");
        int input=sc.nextInt();     
        int i,j;            

        int[]num=new int[(int)(input/2)];

        if(input<=1){
            System.out.print("변환된 수는 "+input+"입니다.");
        }
        else{   

            for(i=0;input>1;i++){
                if(input%2==0){
                    num[i]=0;
                    input=input/2;
                }
                else{   
                    num[i]=1;
                    input=(input-1)/2;
                }
            }

            System.out.print("변환된 수는 "+input);
            for(j=0;j<i;j++){
            System.out.print(num[i-1-j]);
            }
            System.out.print("입니다.");
        }
    }
}

2018/03/14 21:06

배혜민

#십진수를 이진수로 바꾸는 방법은 십진수를 2로 나눠 몫이 1이나 0이될때까지 나머지를 구한다.
#결과로 나온 나머지를 역순으로 뽑아내면 된다.
x = int(input("Enter:"))
a = "" #결과를 저장할 문자열 변수
while x: #x가 참일동안 즉 0이되면 탈출
    a += str(x%2) #문자로 변경 후 문자열 + 연산
    x = int(x/2) #십진수를 2로 계속 나눠줌
print(a[::-1]) #문자열 슬라이싱 역순출력

2018/03/15 17:58

DEMIAN

def binary(num):
    return int(str(bin(num))[2:])

2018/03/20 16:55

yijeong

Swift입니다. String class의 init(T, radix: Int, uppercase: Bool)를 이용했습니다.

import Foundation

print("Enter integer number: ", terminator: " ")
if let decimalString = readLine() {
    if let decimal = Int(decimalString) {
        print("Binary number is \(String(decimal, radix: 2))")
    }
}

2018/03/21 06:22

졸린하마

python 3

#재귀함수
list = []
def hex_to_bin(n):
    list.append(str(n % 2))
    if n == 1:
        list.reverse()
        return
    return hex_to_bin(int(n / 2))

dec_to_bin(73)
print(''.join(list))

#내장함수
print(bin(73)[2:])

2018/04/03 16:12

무명소졸

package com.test;

import java.util.ArrayList;
import java.util.List;

public class decimalToBinary {

    public static void main(String[] args) {

        int decimal = 73;

        toBinary(decimal);
    }

    public static void toBinary(int dec) {

        int temp = dec;

        List<Integer> bin = new ArrayList<Integer>();

        while( temp > 1 ) {                 
            bin.add(temp%2);    
            temp = temp / 2;
        }
        bin.add(1);

        System.out.print("Decimal : " + dec + " to Binary : " );

        for ( int i = bin.size()-1; i >=0; i-- ) {
            System.out.print(bin.get(i));
        }
    }
}

2018/04/30 15:12

聂金鹏

def binary(n):
    if n < 2:
        print(n, end='')
    else:
        binary(n // 2)
        print(n%2, end='')

2018/05/24 21:16

Gerrad kim

n = int(input("숫자를 입력하세요: "))
arr = []
while(n):
    arr.append(str(n%2))
    n = int(n/2)

arr.reverse()
print("".join(arr))

2018/05/28 10:45

bnewkk

Python

test = [73, 22, 254]
for t in test:
    print(str(bin(t))[2:])
#Another version
for t in test:
    ans = ""
    while True:
        ans += str(t%2)
        if t//2 != 0:
            t = t//2
        else:
            break
    print(ans[::-1])

2018/05/31 15:54

Taesoo Kim

num =input("")
result =[]
while 1:
    if int(num) <= int(1):
        result.append(1)
        break
    result.append(int(num)%2)
    num = int(num)/2
result.reverse()
print(''.join(map(str,result)))

2018/06/02 01:13

조성은


number = int(input("어떤 자연수: "))
# 파이썬 내장함수 bin 사용
print(str(bin(number))[2:])

# 알고리즘을 사용
str2 = ''
i = 0
while(number > 2**i):
    i += 1
i -= 1
while(i > -1):
    if number >= 2**i:
        number -= 2**i
        str2 += '1'
    else:
        str2 += '0'
    i -= 1
print(str2)

2018/06/02 04:37

재즐보프

n = int(input("2진법으로 나타낼 수는?"))

print(bin(n)[2:])

2018/06/06 22:27

meteor

num = int(input('10진수: '))
a = 1
result = ''
while a:
    a = num//2
    b = num%2
    num = a
    result = str(b)+result
print('2진수: %s' % result)

2018/06/24 21:53

Creator

a=int(input())

bin(a)[2:]

2018/07/04 23:10

박현우

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        try {
            System.out.println("수를 입력해 주세요");
            Integer n = new Scanner(System.in).nextInt();

            System.out.println(Integer.toBinaryString(n));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2018/08/03 10:38

PuTa

C언어
#include<stdio.h>

void binary(int );

int main()
{
    int num; 
    printf("2진법으로 자연수를 나타 내기 정수를 입력해주세요 : ");
    scanf("%d", &num);
    binary(num);
    return 0;

}

void binary(int n)
{
    if(n>1)
    {
        binary(n/2);
    }
    printf("%d", n%2);
}


2018/08/07 13:31

이우경

Ruby

a = []
b = gets.chomp.to_i
loop do
    a << b % 2
    b /= 2
    break if b == 0
end
puts a.reverse.join

2018/08/24 09:59

아뇩다라삼먁삼보리

def func(test):
    result=[]
    while test >0:
        result.append(str(test%2))
        test=test//2
    result.reverse()
    print("".join(result))

test = int(input('숫자 입력:'))
func(test)


2018/08/24 14:16

S.H

def binary(n):
    result=''
    while n:
        n, r = divmod(n,2)
        result=str(r)+result
    return result

print(bin(20)[2:])

2018/09/11 19:04

전형진

def decitobin(d):

    result = ""
    while d:
        d, r = divmod(d, 2)
            result += str(r)
    result = result[::-1]
    return result

n = int(input())
decitobin(n)

2018/09/15 07:45

Charlie Jeong

def decitobin(n):

    a = int(n)
    l = []
    while a > 0:
        a, c = divmod(a, 2)
        l.append(str(c))
        if a == 0:
            break

    l2 = l[::-1]

    return ''.join(l2)

n = input("type in a deci number: ")
print(decitobin(n))

####
#type in a deci number: 73
# ==> 1001001

2018/09/19 11:04

Charlie Jeong

"""
2진법이란, 어떤 자연수를 0과 1로만 나타내는 것이다.
예를 들어 73은 64(2^6)+8(2^3)+1(2^0)이기 때문에 1001001으로 표현한다.
어떤 숫자를 입력받았을 때 그 숫자를 2진법으로 출력하는 프로그램을 작성하시오.
"""

def to_binary(number):
    if number == 0: return '0'
    if number < 0: raise
    binary_num = ''
    while number > 0:
        binary_num += str(number%2)
        number = number // 2
    binary_num = binary_num[::-1]
    return binary_num

assert to_binary(73) == '1001001'
assert to_binary(1) == '1'
assert to_binary(2) == '10'
assert to_binary(0) == '0'

try:
    input_num = int(input("Input number : "))
    binary_number = to_binary(input_num)
    print("Binary value is :" + binary_number)
except:
    print("Invalid input.")

2018/09/21 22:34

phg98

num1 = int(input('2진수로 변환할 값 : '))
k = []

while num1 > 0:
    k.append(num1%2)
    num1 = num1//2
k.reverse()
print(k)

2018/10/24 04:08

Minho Chu

def chg_binary(N) :
    result=[]
    cnt=0
    for i in range(0,N) :
        if(pow(2,i)<=N and N<pow(2,i+1)):
            cnt=i
            break   
    for i in range(cnt,-1,-1):
        result.append(str((N>>i)&1))

    print("".join(result))

2018/11/05 22:43

쨔이

num=int(input("숫자를 입력하시오:"))
num=bin(num)
num_list=[]
for x in range(2,len(num)):
    num_list.append(num[x])
print("".join(num_list))

2018/11/08 00:42

빅디펜스

de = int(input())

bi = ''
while de >= 1:
    bi += str(de % 2)
    de = int(de / 2) # 파이썬3 이상 자동적으로 실수로 계산

print(bi[::-1])

bi = list(bi) # list(bi).reverse() 안됨
bi.reverse()
print(str(bi)) # '[1, 1, 0, 1]'

print(''.join(bi))

2018/11/08 17:35

그사람 남한 볼 수 있어요

Number = int(input("자연수 입력"))
bi = []

while Number :
    if Number % 2 == 0 :
        bi.append(str(0))
        Number = Number / 2
    else :
        bi.append(str(1))
        Number = (Number - 1) / 2

bi.reverse()

print("".join(bi))

2018/11/29 00:22

lucky1to10

import java.util.Scanner; 

public class KimSanghyeop
{
    public static void main(String[] args)
    {

        Scanner sc = new  Scanner(System.in);
        System.out.print("숫자를 입력하세요 : ");
        int num = sc.nextInt();

        String str="";

        while(num !=0)
        {
            str +=String.valueOf(num %2);
            num = num /2;
        }

        str=new StringBuffer(str).reverse().toString();

        System.out.println(str);
    }
}

2018/12/12 17:30

김상협

def two(num):
    result = []
    while 1:
        if num == 1:
            result.append(1)
            break
        else:
            result.append(num%2)
            num = num // 2
    result.reverse()
    return result

입니다.

2018/12/13 14:16

하이퍼

# decimal_to_binary.py

nums = input("Enter numbers : ").split()
nums = [int(n) for n in nums]

print([format(num, '#b') for num in nums])

2019/01/02 20:01

판다네밥상

#include<stdio.h>


int main(void) 
{
    int num,nam;
    int a[10];
    int cnt = 0;
    int i;
    printf("숫자를 입력하세요:");
    scanf_s("%d", &num);
    do
    {
        nam = num % 2;
        num = num / 2;
        a[cnt] = nam;
        cnt++;



    } while (num / 2 != 0);
    printf("1");
    for (i = cnt-1; i >= 0; i--)
    {
        printf("%d", a[i]);
    }

    return;

}

2019/01/06 19:07

흐긴노노

in_int = int(input("이진수로 변환할 수를 입력하십시오. : "))
bin_lis = []
while in_int > 0:
    bin_lis.append(in_int % 2)
    in_int //= 2

bin_lis = list(reversed(bin_lis))
print(bin_lis)

2019/01/07 19:00

김하마

num = int(input())
bag = []
while num > 0:
    bag.append('{}'.format(num % 2))
    num = int(num/2)
bag.reverse()
print(int(''.join(bag)))

2019/01/21 15:00

D.H.

def ChangeToBinary(number):
    temp=0
    res=""
    while number>1:
        if number % 2 == 1:
            res="1"+res
        else:
            res="0"+res
        number//=2
    res="1"+res
    return res


print(ChangeToBinary(73))

# 풀긴 풀었는데 너무 무식하게 풀었습니다 ㅠ 반성ㅠㅠ


2019/01/21 22:07

얀차

#자연수를 2진법으로 나타내기
ls=['0','1']
k=int(input('자연수 입력: '))
r=[]
while True:
    kr=ls[k%2]
    r.append(kr)
    k=k//2
    if k<2:
        r.append(ls[k])
        r.reverse()
        result="".join(r)#문자열 합치기
        print(2,'진법 변환 후: ',result)
        break

2019/01/27 20:22

GammaKnight

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>

int* getBinary(int num) {
    int tmp = num;
    int exp = 0;
    int base = 1;
    while (base <= tmp) {
        base *= 2;
        exp++;
    }
    int* arr = (int*)malloc(sizeof(int)*exp);
    for (int i = exp - 1; i >= 0; i--) {
        if (tmp % 2 == 1) {
            arr[i] = 1;
            tmp /= 2;
        }
        else {
            arr[i] = 0;
            tmp /= 2;
        }
    }
    return arr;
}
int main() {
    int num;
    scanf("%d", &num);
    int base = 1;
    int length = 0;
    while (base <= num) {
        base *= 2;
        length++;
    }
    int* result = getBinary(num);
    for (int i = 0; i < length; i++) {
        printf("%d", result[i]);
    }
    free(result);
    return 0;
}

2019/02/11 16:38

JohnSuhr

N = int(input("자연수를 입력하시오 : "))
print(bin(N)[2:])

제풀이는 뭐 꼼수네요..

2019/02/14 14:43

임민주

while True:
    n=int(input("Input a number: "))
    bina=[]
    while n!=0:
        bina.append(str(n%2))
        n=n//2
    bina.reverse()
    result="".join(bina)
    print(result)

2019/02/24 11:37

ykleeac

namespace codingdojang__
{
    class Program
    {
        static void Main(string[] args)
        {
            Binary(73);
        }
        static void Binary(int input)
        {
            string binary = "";
            while (input > 0)
            {
                binary += input % 2;
                input /= 2;
            }
            Console.WriteLine(binary);
        }
    }
}

2019/03/12 20:46

bat

비쥬얼 스튜디오 2017로 작성했습니다.

#include <stdio.h>

void main() {

    int dec;
    int bin[16] = { 0, };

    int arraySize = sizeof(bin) / sizeof(int);
    int i = arraySize - 1;

    printf("10진수를 입력하세요 : ");
    scanf("%d", &dec);

    while (true)
    {
        int m = dec / 2;
        bin[i--] = dec % 2;
        if (m == 0)
            break;
        dec = m;
    }

    for (int j = 0; j < arraySize; j++)
    {
        printf("%d", bin[j]);
        if ((j + 1) % 4 == 0)
        {
            printf(" ");
        }
    }
    printf("\n");
}

2019/03/21 17:29

Albert

c로 풀어봤습니다

#include <stdio.h>
int main()
{
    int n,i=0;
    int a[20];
    scanf("%d", &n);
    if(n==0){
    printf("0");
    return 0;
    }
    while(n>=1){
        a[i] = n%2;
        i++;
        n /= 2;
    }

    i -= 1;
    while(i>=0){
        printf("%d",a[i]);
        i--;
        }
    return 0;
}

2019/03/27 22:51

용 빈

def DeciBin(num):
    result = ''
    print(num)

    while num > 0:
        result += str(num % 2)
        num //= 2

    return result[-1::-1]

print(DeciBin(73))



2019/04/01 20:13

ChungGeol You

bitmask 를 이용하였습니다.

#include <iostream>
using namespace std;

int main()
{
    long long int N;
    string str;
    scanf("%lld", &N);

    while(N > 0)
    {
        if(N & 1)
            str = '1' + str;
        else
            str = '0' + str;
        N >>= 1;
    }
    cout << str;
    return 0;

}

2019/05/01 16:48

이기준

def binF(N):
    if N==1 or N==0:
        return N

    m=N;t=0
    while m!=1:
        t+=1;m=int(m/2)

    return 10**t + binF(N-2**t)

print(binF(int(input())))

그러나 굳이 이렇게 복잡하게 하지 않더라도, 파이썬의 내장 함수 중 bin 함수를 쓰면 쉽게 풀리는군요...몰랐었읍니다;;

2019/05/02 16:53

암살자까마귀

n, a =int(input("숫자를 입력하세요: ")), []

while n>0:
    if n%2 == 0:
        a.append('0')  
    else:
        a.append('1')  
    n //= 2
a.reverse()
print(''.join(a))

2019/05/09 22:36

cheer

from collections import deque

def binary(num):
    bin = deque([])
    while num != 0:
        reminder = num %2
        num //= 2
        bin.appendleft(reminder)
    return bin

print(*binary(int(input('2진수로 변환할 10진수를 입력하세요: '))), sep='')

2019/05/18 14:46

Hwaseong Nam

def b(n):
    s = ''
    while n:
        s = str(n % 2) + s
        n = n // 2
    print(s)

2019/05/22 00:52

messi

# 간단한 방법 : 내장함수(bin) 사용
n = int(input("n : "))
print(bin(n)[2:])

def binary(n):
    result = ""
    while(True):
        if n == 1:
            result += str(n)
            break
        result += str(n%2)
        n = n//2
    return result

print(binary(73))

2019/07/06 12:14

최은미

python

n = int(input())
res = []
while True:
    res.append(divmod(n,2)[1])
    n = divmod(n,2)[0]
    if divmod(n,2)[0] == 1:
        res.append(divmod(n,2)[1])
        res.append(divmod(n,2)[0])
        break
''.join([str(x) for x in list(reversed(res))])

2019/08/03 12:28

apriori

import queue
q=queue.LifoQueue()
n=int(input("10진수 자연수 입력:"))
while True:
    q.put(n%2)
    n=n//2
    if n==0:
        break
while q.qsize()!=0:
    print(q.get(),end='')
print('')

2019/08/06 11:55

박재욱

# Algorithm
def Transform(a):
    remainder = []
    while 1:
        remainder.append(a%2); a = int(a/2)
        if a == 0: break
    remainder.reverse(); map_1 = map(str, remainder)
    return ''.join(map_1)
#Input, Output, call the function
print(Transform(a = int(input())))

2019/08/29 14:20

이명운

    class Program
    {
        static void Main(string[] args)
        {
            int Input =  int.Parse(Console.ReadLine());
            string Converter = Convert.ToString(Input, 2);

            Console.WriteLine(Converter);
        }
    }

2019/09/11 09:15

김저승

def num_2(a):
    n = a
    j = []
    while n > 1:
        i = n // 2
        j.append(n % 2)
        n = i
    j.append(i)
    m = ''
    for k in range(0, len(j)):
        f = len(j) - k - 1
        val = j[f]
        m = m + str(val)
    print('10진수 {} --> 2진수 {}'.format(a, int(m)))

2019/09/21 03:45

박주현

tmp = []
a=int(input("2진수로 바꿀 숫자를 넣으시요 : "))
while a>=1:
    a,b = divmod(a,2)
    tmp.append(b)
tmp.reverse()
result = map(str,tmp)
print("".join(result))

2019/10/09 21:57

semipooh

package d139_binary_system;
import java.util.Scanner;
public class BinarySystem {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        long i=1;
        long input = sc.nextLong();
        String output = "";

        for(i=1; i<=input/2; i*=2); //2의 배수 중 인풋보다 크지 않은 최댓값 구하기
        //System.out.println(i);

        for( ; i>0; i/=2) {
            if(input>=i) {
                output+="1";
                input-=i;
            }
            else output+="0";
        }
        System.out.println(output);
    }
}
35
100011

2019/10/14 23:41

Katherine

파이썬

# Conversion to binary
num = int(input("Input any number = "))
s = ""
while num > 1:
    s += str(num % 2)
    num = num // 2
    print(s)
s += "1"
s = s[::-1]

print(s)

"""
num = int(input("Input any number = "))
bin_num = bin(num)
print(bin_num)
"""

2019/10/15 18:31

Jzay

def num(a):
    return bin(a)

print(num(a)) # 2진수 출력 후 앞에  0b는 2진수로 나타내었을 때 뒤에 정수로
나타날 수 있다는 뜻

# a에는 숫자가 들어가면 됨

파이썬의 bin이라는 함수를 이용해 간단히 완료!

2019/11/06 21:32

박지훈

import java.util.*;
public class 이진법으로자연수나타내기 {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        int num = scan.nextInt();
        System.out.println(Integer.toBinaryString(num));
    }
}

2019/11/08 17:28

big Ko

파이썬 입니다.

def binary(num):
  binar=[]
  while True:
    if int(num)%2==0:
      binar.append('0')
    elif int(num)%2==1:
      binar.append('1')
    num = int(num)//2
    if int(num)==0:
      break
  return ''.join(binar.__reversed__())

print(binary(73))  #1001001
print(binary(8))   #1000

2019/11/18 23:06

data big

def dec2bin(num):
    bl = []
    while num != 0:
        bl.insert(0, str(num%2))
        num = int(num/2)

    return ''.join(bl)

print(dec2bin(73))

2019/11/19 17:29

Nonamed

파이썬입니다.

n = int(input('숫자를 입력하시오: '))
format(n,'b')

2019/12/20 16:33

Sean

int FdecimalTbinary(int n)
{
int result = 0;
int temp = 1, temp2 = 1;
int counter = 0;
int *tempInverseArray = new int;
while(n>temp&&n!=0)
{
temp2 = temp * 2; counter ++;
n =< temp2 ? n = n-temp2, tempInverseArray[counter] = 1, temp = 1, temp2 = 1, counter = 0 :temp = temp2 ; 
}
counter = sizeof(tempInverseArray) / sizeof(int);
int resultArray[counter];
for(int i = 0;i<counter;i++)
{
resultArray[i] = tempInverseArray[counter-i];
}
delete tempInverseArray;
return result;
}

2019/12/23 03:55

Anderson

def binary(x):
    if x == 0:
        return ''
    else:
        return binary(x // 2) + str(x % 2)

2019/12/23 11:01

김민규

a=int(input("2진수로 바꿀 값:"))

c=[]
while a>0:
    c.append(a%2)
    a=int(a/2)

c.reverse()
c = [str(x) for x in c]
print(''.join(c))

2019/12/23 19:28

뚜루꾸까까

n=int(input("자연수 n을 입력하십시오: ")) #73
elst=[]
while True:
    elst.append(n%2)
    n=int(n/2)
    if n==0:
        break
elst.reverse()
num=[str(i) for i in elst]
print("".join(num))  #1001001

2019/12/31 12:20

박시원

bin(int(input('INPUT : ')))[2:]

결과

INPUT : 255
'11111111'

2020/01/14 16:46

GG

tmp = 0
def binary(someint):
    global tmp
    for i in range(10000):
        if someint < 2 ** (i+1) and someint>= 2** (i):
            tmp += 10 ** (i)
            binary(someint-(2**i))
        elif someint > 2 ** i:
            continue
        else :
            break
    return print(tmp)
binary(3) 

2020/01/22 17:27

H

a = bin(int(input("수를 입력: ")))

print(a[2:])


2020/01/27 22:24

김희준

import java.util.Scanner;

public class BinaryPrint2 {
    public static void main(String[] args) {
        Scanner Sc = new Scanner(System.in);
        BinaryPrint2 BP = new BinaryPrint2();

        System.out.print("숫자를 입력하시오 :");
        int input = Sc.nextInt();
        BP.Binary(input);
        Sc.close();
    }
    void Binary(int n) {            //재귀함수를 이용한 이진법 구하기
        if(n==0) {
            return;
        }
        else {
            System.out.print(n%2);
            Binary(n/2);
        }
    }
}

2020/01/30 22:51

김강민

n = int(input("Enter the Number:"))

namerzi = []

while n>=1:

    namerzi.append(n%2)

    n=n//2

namerzi.reverse()

for i in namerzi:

    print(i,end='')

2020/02/05 15:42

HyukHoon Kim

a = int(input())

b = bin(a)[2:] print(b)

2020/02/19 17:21

이국성

n=int(input())
result=''
while n>0:
    result = str(n%2)+result
    n=n//2

print(result)

2020/03/07 09:25

황예진

def n_binary(m, n):
    result=0
    i=1
    while m!=0:
        result+=m%n*10**(i-1)
        m=m//n
        i+=1
    return result

문제를 일반화해서 10진법 정수 m 을 n진법 정수로 나타내보도록 작성했습니다.

2020/03/08 00:02

Caplexian _

dec=int(input())
bin=[]
n=0
print(dec,'=',end='')

while (dec>0):
bin.append(dec%2)
dec=dec//2
n=n+1

while (n>0):
n=n-1
print(bin[n],end='')

2020/03/10 00:54

Buckshot

def binary(n, blist): if n<2: blist.append(str(n)) return else: blist.append(str(n%2)) return binary(n//2,blist)

n=int(input("십진수 입력>>>")) rest=[] binary(n,rest) rest.reverse() result=''.join(rest) print(result)```{.python}

```

2020/03/19 12:15

배기경

l=[]
f=[]
def t(n):
    #print('함수 시작')
    #print('n은'+str(n))
    i=-1
    while n>0:
        i+=1
        #print('시도해볼 i는 '+str(i)+'입니다.')
        if 2**i<=n<2**(i+1):
            l.append(i)
            #print('성공한 i는 '+str(i)+'입니다.')
            n-=2**i
            #print('n은 '+str(n)+'입니다.')
            t(n)
            break
        else:
            pass
t(838)
#print('2진법 지수 리스트는 '+str(l)+'입니다.')
if l!=[]:
    for i in range(l[0]+1):
        f.append(0)
    #print(f) 빈 리스트 생성
    for i in l:
        #print(i)
        f[i]=1
    f.reverse()
    #print(f) 최종 리스트 출력
    F=[]
    for i in f:
        F.append(str(i))
    print(''.join(F))
else:
    print(0)

풀면서 여러가지 풀이방법을 생각해보았습니다. 그 중에서 가능한한 사람과 비슷한 방식으로 계산하도록 만드려고 노력했습니다. 사람의 사고방식에 대해서도 잘 알지 못하는 탓에 바라던 만큼 비슷하게 하지는 못했지만, 알고 있다고 생각했던 사람의 연산방식에 대해 확실하지 않은 부분이 있다는 생각을 했습니다. 또 재귀 함수의 작동 방식에 대해 조금 더 구체적으로 알게 되었습니다. 이 문제는 앞으로 한번씩 다시 보면서 더 연구해보면 코딩 사고력 발달에 많은 도움이 될 것 같습니다. 흥미로운 문제를 올려주셔서 감사합니다! ^^

2020/03/31 00:45

di figo

num=int(input("정수 입력 : "))
binary=[]
while num>0:
    if num%2==0:
        binary.append(0)
    else:
        binary.append(1)
    num=int(num/2)

for i in range(len(binary)-1,-1,-1):
    print(binary[i],end="")

2020/04/21 22:41

kim center

d = int(input('수 : '))

b = []
while d != 1:
    if d % 2 == 0:
        b.insert(0, 0)
    else:
        b.insert(0, 1)
        d -= 1
    d /= 2
b.insert(0, d)

for i in range(len(b)):
    print(int(b[i]), end='')

파이썬

2020/04/23 20:43

Shiroha

a=int(input('십진수 입력하면 이진수로 바꿔드림 : '))
b=bin(a)
print(b[2:])

2020/04/23 21:33

양양짹짹

import java.util.ArrayList;
import java.util.Scanner;

public class Q139{
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("Input Decimal Number : ");
        int deci = scan.nextInt();

        ArrayList<Integer> bn = new ArrayList<Integer>();
        while(deci!=0) {
            if(deci%2==0) bn.add(0);
            else if(deci%2==1) bn.add(1);
            deci = deci/2;
        }
        System.out.print("Binary Number : ");
        for(int i=bn.size()-1; i>=0; i--) System.out.print(bn.get(i));

        scan.close();
    }
}

2020/05/06 21:01

Daniel Park

def convert_binary(n):
    remainders = []
    target = n
    while target > 1:
        target, remainder = divmod(target, 2)
        remainders.append(remainder)
    remainders.append(1)
    return int("".join([str(i) for i in remainders[::-1]]))

2020/05/07 17:19

김준혁

x = int(input()) 
change = bin(x)[2:]
print(change)

2020/05/08 16:47

Money_Coding

def binary(n):
    return bin(n)[2:]
N=int(input())
print(binary(N))

2020/05/10 14:57

도희성

a = int(input("숫자를 입력하세요>> "))

print("입력하신 숫자는 {:b}입니다.".format(a))

2020/06/23 18:06

찌끅

namespace _60일차_9월30일
{        
    class MainApp
    {
        static void Main(string[] args)
        {

            Console.Write("Input Number  : ");
            string input = Console.ReadLine();
            int data = Convert.ToInt32(input);

            Console.WriteLine(Convert.ToString(data, 2));
        }
    }
}

2020/09/30 18:45

MinSeung Kang

n=int(input())
q=0
r=''
while True:
    if n//2!=0:
        q=n//2
        r+=str(n%2)
        n=q
    else:
        if n%2==1:
            r+=str(n%2)
        break
print(r[::-1])

2020/10/09 11:15

AppleFarmer

class CalBinary:
    def __init__(self):
        self.result = 0
    def doBinary(self,n):
        i = 0
        while True:
            if n<2**i:
                rem = n%2**(i-1)
                self.result += 10**(i-1)
                if rem==0:
                    break
                else:
                    n = rem
                    i = 0
            i += 1
        print (self.result)

a = CalBinary()
a.doBinary(73)

2020/10/12 22:52

footsize

#include<stdio.h>
#include<math.h>

int main()
{
    int input;
    int output=0;
    int i=0;
    scanf("%d",&input);

    while(1)
    {
        output=output+input%2*pow(10,i);
        input=input/2;
        i++;
        if(input<1) break;
    }
    printf("%d",output);
    return 0;
}

2020/10/13 23:39

June

N = int(input())
Nfinal = ""
while True:
    if N == 1 or N == 0:
        Nfinal += str(N)
        break
    else:
        Nfinal += str(N%2)
        N = int((N-(N%2))/2)
print(Nfinal)

2020/11/08 14:36

BlakeLee

def binary(num):
    result = []
    temp = int(num)
    while temp >= 2:
        result.append(str(temp%2))
        temp = int(temp//2)
    result.append(str(temp))
    result.reverse()
    return "".join(result)

num = int(input('NUMBER : '))
print(binary(num))

2020/11/17 08:50

DSHIN

print(bin(int(input("정수를 입력하세요:")))[2:])

2020/11/19 14:37

김우석

# Python
def binary_num(given_num):
    """Convert the given number to a binary number."""
    # Empty list to store remainders and a last quotient.
    binary_num_list = []

    while True:
        # Assign remainder and dividend which will be used at next 'while loop'.
        # Until it(divident) reaches down to 1.
        remainder = given_num % 2
        given_num = given_num // 2

        binary_num_list.append(remainder)
        if given_num == 1:
            binary_num_list.append(1)
            break

    binary_num_list.reverse()
    binary_num_list = [str(x) for x in binary_num_list]
    return int(''.join(binary_num_list))

binary = binary_num(58375839439)
>>> 110110010111011110001001111011001111
print(binary)

2020/11/22 22:23

방금프로그래밍시작함

number=int(input("write your number :"))

k=number

for_answer=[]

while number:

  for_answer.append(number%2)

  number=int(number/2)

for_answer.reverse()

for_answer=[str(x) for x in for_answer]

print("".join(for_answer))

2020/12/02 12:19

전준혁

import java.util.Scanner;

public class Binary {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        System.out.println("변경 할 수 : ");
        int n = sc.nextInt();
        String re = Integer.toBinaryString(n);
        System.out.println("2진수 : "+re);

    }

}

2020/12/10 16:57

이정섭

def dtb(n):
    arr = []
    while 1:
        if(n // 2 != 1):
            arr.append(n % 2)
            n = n // 2
        else:
            arr.append(n % 2)
            arr.append(n // 2)
            arr.reverse()
            result = "".join(list(map(str,arr)))
            return result


n = int(input())
result = dtb(n)
print(result)

2020/12/17 23:42

guma go

def binary(n):
    i =0
    sq =[]
    while True:
        if n-2**i>0:
            i+=1
        elif n-2**i==0:
            sq.append(i)
            break
        else :
            sq.append(i-1)
            n-=2**(i-1)
            i=0
    result = eval('+'.join(['1'+'0'*x for x in sq]))

    return result

2020/12/23 23:27

hankyu

num = int(input("자연수 n을 입력하세요:"))

result = 0
list = []
new_num = ''

#최대 승수 구하기 
i = 0
while 2 ** i <= num:
    i += 1
j = i - 1

#자연수 N에 포함되는 2의 승수들 리스트로 뽑기
for a in range(new_i, -1, -1):
    if 2 ** a <= num:
        result += 2 ** a
        num -= 2 ** a
        list.append(a)
    elif result == num:
        break

#리스트 안에 있는 숫자들을 2진수로 변경
for i in range(list[0], -1, -1):
    if i not in list:
        new_num += str('0')
    else:
        new_num += str('1')

print(new_num)

2021/01/08 13:16

코딩뚜

n=int(input())
b=''

while n:
    b+=str(n%2)
    n=n//2
print(b)

2021/01/19 13:52

손우민

def leejinbub():
    N = int(input('Number : '))
    N2 = '1'
    A = N
    temp = []
    while 1:
        A1 = str(A/2).split('.')[0]
        A2 = str(A/2).split('.')[1]
        A = int(A1)
        if A2 == '5':
            temp.append('1')
        elif A2 == '0':
            temp.append('0') 
        if A1 == '1' or A1 == '0':
            break
    for i in range(len(temp)):
        N2 = N2 + temp[(len(temp)-1)-i]

    print(N2)


def main():
    leejinbub()

if __name__ == '__main__':
    main()

2021/02/02 11:40

서해원

def f(x):
    if x == 1:
        return '1'
    return  f(x // 2) + str(x % 2)

2021/02/04 16:42

Ha

x = int(input())
output = ''

while x > 1:
    output += str(x%2)
    x = x//2
output += '1'

print(output[::-1])

2021/02/06 13:23

asdfa

a=73
b=[]
while a>=1:
    if a%2==1:
        b.append('1')
    else:
        b.append('0')
    a//=2

b.reverse()
print(''.join(b))

2021/02/09 21:57

fox.j

#1
n = 12
result,res2 = [],[]
n1 = 0

for k in range(0,10):
    n1 = int(n/(2**k))
    result.append(n1)

for i in result:
    if i !=0:
        res2.append(str(i%2))

res2.reverse()
print("".join(res2))

#2
res = []
n = 73
while n:
    res.append(str(n%2))
    n = int(n/2)

res.reverse()
print("".join(res))

2021/02/10 22:48

개촙오

n=int(input('숫자 입력'))

result=''                
process=n
save=0
x=0

while True:
    x += 1
    if 2**(x+1) > n:
        break

for i in range(x, -1, -1):
    process = process - 2**i
    if process > 0:
        result+='1'
    if process == 0:
        result+='1'
        for y in range(i):
            result+='0'
        break
    if process < 0:
        result+='0'
        process=save
    save=process

print(result)

정말 머리를 싸매면서 어떻게 구현해낸 알고리즘인데... 그냥 주어진 자연수를 2로 계속 나눠서 그 나머지들을 통해 2진법으로 구현하는 방법이 있었네요. 2진법으로 변환하는 방법을 잘 알고 있다면 쉽게 풀었을 법한 문제인 것 같습니다(수포자는 오늘도 웁니다...).

2021/02/28 12:13

최우진

n = int(input('숫자입력: '))
result = ''
num = n
while num >= 1:
    result = str(num % 2) + result
    num = num // 2

print(result)

2021/03/27 00:10

잘해보자

Python입니다.

>>> def to_bin(n):
    l = []
    d = n
    while d > 0:
        d, m = divmod(d, 2)
        l.insert(0, str(m))

    return ''.join(l)

>>> to_bin(73)
'1001001'

리스트를 썼는데, Noname 님처럼 문자열을 바로 쓰는 게 나아 보입니다.

2021/04/11 21:00

최용

def bin_func(input_num):
    a=int(input_num)
    out=[]
    while a:
        out.append(a%2)
        a=int(a/2)
    return "".join(map(str,out[::-1]))

2021/04/26 15:56

최태호

n = 73
new = []
while n:
    new.append(n%2)
    n = n//2
new.reverse()
print(new)

2021/05/10 23:31

ss2663

def make_bi_number():
    given_number = int(input("2진수로 바꿀 숫자를 입력해 주세요."))
    bi_list = []

    while True: #거꾸로 된 2진법 수열 list 구하기.
        if given_number%2 == 0:
            bi_list.append(0)
            given_number/=2
        elif given_number%2 ==1:
            bi_list.append(1)
            given_number = (given_number-1)/2
        if given_number <= 0:
            break
    bi_list.reverse() #정렬

    bi_string = ''
    for i in bi_list: #str 값으로 바꾸어 주기
        bi_string+=str(i)
    return bi_string

2021/06/23 18:05

inkuk ju

def func():
    user_input = input('Input hex data: ')
    list = []
    a = int(user_input)
    if a == 1:
        list.append(str(1))
    else:
        while a != 1:
            if int(a) % 2 == 0:
                list.append(str(0))
            elif int(a) % 2 == 1:
                list.append(str(1))
            a = a / 2
            if a == 1:
                list.append(str(1))
                break
    list.reverse()
    print(''.join(list))

2021/07/07 16:53

김준규

def binary(x):print("Binary of decimal {0} is {0:b}".format(x))

2021/07/12 12:47

billy han

#codingdojing_binaryCode


#쉬운 방법

def binCh1(n):

    print(bin(n)[2:])

#직접 짜는 방법

def binCh2(n):
    binChr = ''

    while n > 0:
            i,j = divmod(n,2)
            binChr = str(j) + binChr
            n = i

    print(binChr)

for i in range(8,17):
    binCh1(i)
    binCh2(i)

2021/07/12 15:40

Jaeman Lee

python 3.9.6입니다. 10진수를 n진수로 변환하는 프로그램을 만든 뒤, n을 2로 고정하면 됩니다.

origin = int(input('변환할 10진수를 입력하세요. '))
q = origin
r = 0
result = ''

while q != 0:
    r = q % 2
    result += str(r)
    q //= 2
result = result[::-1]
while result[0] == 0:
    result = result[1:]

print(f'변환된 값은 {int(result)}입니다.')

실행 결과입니다.

변환할 10진수를 입력하세요. 73
변환된 값은 1001001입니다.

2021/07/15 11:51

이준우

python 3.2.10으로 작성되었습니다.

num = int(input())
q = num
result = []

while q:
    val = divmod(q, 2)
    q = val[0]
    result.append(str(val[1]))

print(''.join(reversed(result)))


2021/07/26 17:44

baek choi

n=int(input())

result=""
while n>1:
    result+= str(n%2)
    n = n//2


print(result + str(n))

2021/08/24 14:39

서현준

n=input('자연수 : ')
result=''
while n:
    n,r=divmod(int(n),2)
    result=str(r)+result
print(result)

2021/09/17 20:31

ninanino

num = int(input('자연수를 입력해 주세요 : '))

list = []

if num == 0 or num == 1:
    list.append(num)

else:
    the_rest = num % 2   # 첫 나머지
    share = num // 2    # 첫 몫


list.append(the_rest)

while 1:

    if share == 0 or share == 1:
        list.append(share)
        break

    else:
        the_rest = share % 2   
        share = share // 2    

    list.append(the_rest)

list.reverse()

print(list)

2021/09/25 18:27

cripto gazua

static void binary(int x) {
        String str = "";
        while (x > 0) {
            str += x % 2;
            x = x / 2;
        }
        for (int i = 0; i < str.length(); i++) {
            System.out.print(str.charAt(str.length() - i - 1));
        }
        System.out.println();
    }

    public static void main(String[] args) {
        binary(10);
        binary(9);
        binary(8);
        binary(875132);
    }

2021/10/24 14:04

박대현

input_dec = int(input("자연수를 입력하세요 : "))
length = len(str(input_dec))
arr = []
for i in range(length*3):
    if input_dec == 1 or input_dec == 0:
        arr.append(input_dec)
        arr.reverse()
        break

    arr.append(input_dec%2)
    input_dec = input_dec//2



for i in arr:
    print(i, end="")

2021/11/26 10:22

정설경


n = int(input())

b =[]
def bit (a) :
    while a != 0 :
        b.append(a%2)
        a = a//2
    print(list(reversed(b)))


bit(n)

2021/12/17 00:18

양캠부부

x, n = 73, -1
l1 = []
while x != 0:
    while x // 2 ** n != 0:
        n += 1
    x -= 2 ** (n-1)
    l1.append(n)
    n = 0
l2 = ['0'] * l1[0]
for x in l1:
    l2[-x] = '1'
print(int(''.join(l2)))

2021/12/22 00:32

0 o

n = int(input('2진법으로 표현할 수를 입력하시오.'))
print(bin(n)[2:])

2022/01/24 16:18

로만가

input_dec = int(input("십진수 입력 :"))
output_bin = []

while True:
    if(input_dec//2 == 0 or input_dec//2 ==1):
        output_bin.append(input_dec%2)
        output_bin.append(input_dec//2)
        output_bin.reverse()
        break;

    output_bin.append(input_dec%2)
    input_dec = input_dec//2

for i in output_bin:
    print(i, end = '')

2022/02/16 10:27

seolgyung jeong

a = int(input())
b = []
while a:
    b.append(a%2)
    a = int(a/2)
b.reverse()
for i in b:
  print(i,end='')

2022/04/02 11:59

DongWoo

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void)
{
    int x;

    printf("정수를 입력하시오");
    scanf("%d", &x);

    while (x >= 1)
    {
        printf("%d", x % 2);
        x = x / 2;
    }
    return 0;
}

2022/04/15 01:06

두바이강

def binary(N):
    result = []
    while N:
        result.append(str(N%2))
        N = N//2
    return ''.join(result)


num = int(input(':'))
print(binary(num))

2022/05/02 21:41

고구마츄

decimal=int(input()) binary=[] while True: binary.append(int(decimal%2)) decimal/=2 if int(decimal)==0: break binary=reversed(binary) result="".join(str(_) for _ in binary) print(result)

2022/05/04 19:50

권덕재

package com.algorithm.algorithmpractice.dojang;

public class Binary {
    public static void main(String[] args) {
        int[] arr = new int[99];
        int input = 1234123431;
        int temp = input;
        int i = 0;
        while (temp / 2 != 0){
            arr[i] = (temp % 2);
            System.out.println(arr[i]);
            temp /= 2;
            i++;
        }
        arr[i] = temp%2;
        StringBuffer sb = new StringBuffer();
        for(; i >= 0; i--){
            sb.append(arr[i]);
        }
        System.out.println(sb.toString());
    }
}

2022/05/05 12:15

inkuk ju

파이썬입니다.

# 십진수 -> 이진수

def dici_bi(a):
    result = str()
    if a == 0: return '0'
    while a != 0:
        result = str(a%2) + result
        a = a//2
    return result

# 이진수 -> 십진수

def bi_dici(a):
    result = 0
    count = len(a)
    for i in a:
        count -= 1
        if i == '1':
            result += (2 ** count)
    return result

2022/06/09 13:52

김시영

cmd = int(input("2진수로 변환할 정수를 입력하시오:"))

print(bin(cmd)[2:],"(2)")       #(2)를 통해 2진법임을 표시

파이썬으로 작성했습니다.

2022/07/10 23:51

박종훈

def convert_bin(n):
    r = []
    while n >= 1:
        r.append(str(n%2))
        n = n // 2
    r.reverse()
    return ''.join(r)        # r이 리스트인 경우 요소가 str여야 join 적용가능

ui = int(input("2진법으로 나타낼 자연수 입력>> "))
print(convert_bin(ui))

+) 첨부터 문자열로

def convert_bin(n):
    r = ''
    while n >= 1:
        r += str(n%2)
        n = n // 2
    return r[::-1]

ui = int(input("2진법으로 나타낼 자연수 입력>> "))
print(convert_bin(ui))

2022/07/14 23:19

Estelle L

python

num = int(input("숫자를 입력하시오: "))

print(str(bin(num))[2:]) #내장 함수 bin()을 통해 2진수로 변환

x = num
result = []

while x/2 != 0:
    result.append(x%2) 
    x = x//2

result.reverse()
print(''.join(map(str, result))) #정수를 문자열로 변환한 후 하나의 문자열로 반환

2022/08/30 11:29

세라

package ex;

import java.util.Scanner;

public class Ex02 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("숫자 입력");
        int num = sc.nextInt(); 
        String binary = Integer.toBinaryString(num);
        System.out.println(binary);
    }

}

2022/08/31 14:43

Jay Choi

print(str(bin(int(input())))[2:])

Python

2023/01/05 16:55

마라떡볶이

num = int(input("NUM:"))
_bin_ = [];result = []
remain = 0

while num > 1:
   _bin_.append(num % 2)
   num = num //2
_bin_.reverse()
print(('').join(map(str,_bin_)))

2023/08/22 18:07

siu yoon

stack = []
num = int(input())
old_num = num
renmainder = num%2
quotient = num//2
while quetient > 1:
    stack.append(remainder)
    remainder = quotient % 2
    quotient = quotient // 2
if quotient == 1:
    stack.append(remaingder)
    stack.append(1)
while stack != []:
    print(stack.pop(), end ='')

2024/07/03 23:33

정채원

a = int(input("원하는 숫자: "))

if a == 0:
    print("0")
else:
    bits = []
    while a > 0:
        bits.append(str(a % 2))
        a //= 2
    bits.reverse()
    print("".join(bits))

2026/01/03 19:52

k

data = int(input('Enter number: '))
result = []

while data:
    r = data % 2
    data = data // 2
    result.append(str(r))

print(''.join(reversed(result)))

2026/05/14 23:21

우영재

목록으로