logo

10진수를 2진수로 변환하는 프로그램

입력으로 십진수가 주어지면 주어진 십진수를 동등한 이진수로 변환하는 프로그램을 작성해야 합니다.

자바 동적 배열

10진수를 2진수로 :

  Input : 7 Output : 111 Input : 10 Output : 1010 Input: 33 Output: 100001>
권장 연습십진수를 이진수로 바꿔보세요!

무차별 접근 방식

예를 들어 :
십진수가 10인 경우.
1 단계 : 10을 2로 나눈 나머지는 0입니다. 따라서 arr[0] = 0입니다.
2 단계 : 10을 2로 나눕니다. 새로운 숫자는 10/2 = 5입니다.
3단계 : 5를 2로 나눈 나머지는 1입니다. 따라서 arr[1] = 1입니다.
4단계 : 5를 2로 나눕니다. 새로운 숫자는 5/2 = 2입니다.
5단계 : 2를 2로 나눈 나머지는 0입니다. 따라서 arr[2] = 0입니다.
6단계 : 2를 2로 나눕니다. 새로운 숫자는 2/2 = 1입니다.
7단계 : 1을 2로 나눈 나머지는 1입니다. 따라서 arr[3] = 1입니다.
8단계 : 1을 2로 나눕니다. 새로운 숫자는 1/2 = 0입니다.
9단계 : 숫자는 = 0이 되므로 배열을 역순으로 인쇄합니다. 따라서 동등한 이진수는 1010입니다.



아래 다이어그램은 10진수 17을 해당하는 2진수로 변환하는 예를 보여줍니다.

10진수를 2진수로




아래는 위의 아이디어를 구현한 것입니다.

C++
// C++ program to convert a decimal // number to binary number #include  using namespace std; // function to convert decimal to binary void decToBinary(int n) {  // array to store binary number  int binaryNum[32];  // counter for binary array  int i = 0;  while (n>0) { // 나머지를 이진 배열에 저장 BinaryNum[i] = n % 2;  n = n/2;  나++;  } // 이진 배열을 역순으로 인쇄합니다. for (int j = i - 1; j>= 0; j--) cout<< binaryNum[j]; } // Driver program to test above function int main() {  int n = 17;  decToBinary(n);  return 0; }>
// C Code to convert Decimal number into Binary #include  void decToBinary(int n) {  // array to store binary number  int binaryNum[32];    // counter for binary array  int i = 0;  while (n>0) { // 나머지를 이진 배열에 저장 BinaryNum[i] = n % 2;  n = n/2;  나++;  } // 이진 배열을 역순으로 인쇄 for (int j = i - 1; j>= 0; j--) printf('%d', bininNum[j]); } // 위 테스트를 위한 드라이버 프로그램 function int main() { int n = 17;  decToBinary(n);  0을 반환합니다. }>
자바
// Java program to convert a decimal // number to binary number import java.io.*; class GFG {  // function to convert decimal to binary  static void decToBinary(int n)  {  // array to store binary number  int[] binaryNum = new int[32];  // counter for binary array  int i = 0;  while (n>0) { // 나머지를 이진 배열에 저장 BinaryNum[i] = n % 2;  n = n/2;  나++;  } // 이진 배열을 역순으로 인쇄합니다. for (int j = i - 1; j>= 0; j--) System.out.print(binaryNum[j]);  } // 드라이버 프로그램 public static void main(String[] args) { int n = 17;  decToBinary(n);  } } // 제공: Pramod Kumar>
씨#
// C# program to convert a decimal // number to binary number using System; public class GFG {  // function to convert decimal  // to binary  static void decToBinary(int n)  {  // array to store binary number  int[] binaryNum = new int[32];  // counter for binary array  int i = 0;  while (n>0) { // 나머지를 // 이진 배열에 저장 BinaryNum[i] = n % 2;  n = n/2;  나++;  } // 이진 배열 인쇄 // 역순 for (int j = i - 1; j>= 0; j--) Console.Write(binaryNum[j]);  } // 드라이버 코드 public static void Main() { int n = 17;  decToBinary(n);  } } // 이 코드는 Sam007이 제공한 것입니다.>
자바스크립트
>
PHP
 // PHP program to convert a decimal // number to binary number // function to convert // decimal to binary function decToBinary($n) { // array to store // binary number $binaryNum; // counter for binary array $i = 0; while ($n>0) { // 나머지를 // 이진 배열에 저장 $binaryNum[$i] = $n % 2; $n = (int)($n / 2); $i++; } // 이진 배열 인쇄 // 역순 for ($j = $i - 1; $j>= 0; $j--) echo $binaryNum[$j]; } // 드라이버 코드 $n = 17; decToBinary($n); // 이 코드는 m_kit에서 제공한 것입니다. ?>>
파이썬3
# Python3 program to convert a  # decimal number to binary number # function to convert # decimal to binary def decToBinary(n): # array to store # binary number binaryNum = [0] * n # counter for binary array i = 0; while (n>0): # 나머지를 # 이진 배열에 저장 BinaryNum[i] = n % 2 n = int(n / 2) i += 1 # 이진 배열을 # 역순으로 인쇄 for j in range(i - 1, -1, -1): print(binaryNum[j], end = '') # 드라이버 코드 n = 17 decToBinary(n) # 이 코드는 mits에 의해 제공됨>

산출
10001>

시간 복잡도: 오(로그인) & 보조 공간: 오(1)

위의 작업을 수행하기 위해 비트 연산자를 사용할 수 있습니다. 비트 연산자는 위에서 사용된 산술 연산자보다 빠르게 작동합니다.

C++
// CPP program to Decimal to binary conversion // using bitwise operator // Size of an integer is assumed to be 32 bits #include  using namespace std; // Function that convert Decimal to binary void decToBinary(int n) {  // Size of an integer is assumed to be 32 bits  for (int i = 31; i>= 0; i--) { int k = n>> i;  if (k & 1) cout<< '1';  else  cout << '0';  } } // driver code int main() {  int n = 32;  decToBinary(n); }>
// C language to convert Decimal to binary number // using bitwise operator // Size of an integer is assumed to be 32 bits #include  // Function that convert Decimal to binary int decToBinary(int n) {  // Size of an integer is assumed to be 32 bits  for (int i = 31; i>= 0; i--) { int k = n>> i; // 오른쪽 시프트 if (k & 1) // 첫 번째 비트의 상태를 아는 데 도움이 됩니다. printf('1');  그렇지 않으면 printf('0');  } } // 드라이버 코드 int main() { int n = 32;  decToBinary(n); }>
자바
// Java program to Decimal to binary conversion // using bitwise operator // Size of an integer is assumed to be 32 bits class gfg {  // Function that convert Decimal to binary  public void decToBinary(int n)  {  // Size of an integer is assumed to be 32 bits  for (int i = 31; i>= 0; i--) { int k = n>> i;  if ((k & 1)> 0) System.out.print('1');  else System.out.print('0');  } } } class geek { // 드라이버 코드 public static void main(String[] args) { gfg g = new gfg();  정수 n = 32;  g.decToBinary(n);  } } // 이 코드는 mits에 의해 제공되었습니다.>
씨#
// C# program to Decimal to binary conversion // using bitwise operator // Size of an integer is assumed to be 32 bits using System; class gfg {  // Function that convert Decimal to binary  public void decToBinary(int n)  {  // Size of an integer is assumed to be 32 bits  for (int i = 31; i>= 0; i--) { int k = n>> i;  if ((k & 1)> 0) Console.Write('1');  else Console.Write('0');  } } } class geek { // 드라이버 코드 public static int Main() { gfg g = new gfg();  정수 n = 32;  g.decToBinary(n);  0을 반환합니다.  } }>
자바스크립트
>
PHP
 // PHP program to Decimal to binary conversion // using bitwise operator // Size of an integer is assumed  // to be 32 bits // Function that convert Decimal to binary function decToBinary($n) { // Size of an integer is // assumed to be 32 bits for ( $i = 31; $i>= 0; $i--) { $k = $n>> $i; if ($k & 1) echo '1'; 그렇지 않으면 에코 '0'; } } // 드라이버 코드 $n = 32; decToBinary($n); // 이 코드는 aj_36이 제공한 것입니다. ?>>
파이썬3
# Python3 program to Decimal # to binary conversion using # bitwise operator # Size of an integer is # assumed to be 32 bits # Function that convert # Decimal to binary def decToBinary(n): # Size of an integer is # assumed to be 32 bits for i in range(31, -1, -1): k = n>> i if (k & 1): print('1', end='') else: print('0', end='') # 드라이버 코드 n = 32 decToBinary(n ) # 이 코드는 mits에 의해 제공되었습니다.>

산출
00000000000000000000000000100000>

시간 복잡도: 오(1)

루프는 작은 숫자라도 매번 상수(32)번 반복합니다.



보조 공간: 오(1)

효율적인 접근 방식

이는 오른쪽 Shift(>>) 및 And(&) 연산자를 사용하여 10진수를 2진수로 변환하는 또 다른 효율적인 접근 방식입니다. 여기서는 일반적으로 계산 속도가 매우 빠른 이진 연산자만 사용합니다.

C++
#include  using namespace std; string DecimalToBinary(int num) {  string str;  while(num){  if(num & 1) // 1  str+='1';  else // 0  str+='0';  num>>=1; // 오른쪽으로 1만큼 시프트 } return str; } void reverse(string str) { for(int i=str.size()-1 ; i>=0 ; i--) cout<< str[i];  } int main() {  int num = 59;  cout<< 'Binary of num 59 is: ';  reverse( DecimalToBinary(num) );  return 0; }>
자바
// Java program to implement the // above approach import java.io.*; class GFG  {  // the converts decimal to binary base  static String DecimalToBinary(int num)  {  String str = '';  while (num>0) { if ((num & 1) == 1) // 1 str += '1';  else // 0 str += '0';  숫자>>= 1; // 오른쪽으로 1만큼 시프트 } return str;  } // 문자열 반전 static void reverse(String str) { for (int i = str.length() - 1; i>= 0; i--) System.out.print(str.charAt(i));  } 공개 정적 void main(String[] args) { int num = 59;  System.out.print('숫자 59의 이진수: ');  reverse(DecimalToBinary(num));  } } // 이 코드는 phasing17에서 제공한 것입니다.>
씨#
// C# program to implement the // above approach using System; public class GFG {    // this converts decimal to binary base  public static string DecimalToBinary(int num)  {  string str = '';  while (num>0) { if ((num & 1) == 1) // 1 str += '1';  else // 0 str += '0';  숫자>>= 1; // 오른쪽으로 1만큼 시프트 } return str;  } // 문자열 반전 public static void reverse(String str) { for (int i = str.Length - 1; i>= 0; i--) Console.Write(str[i]);  } // 드라이버 코드 public static void Main(string[] args) { int num = 59;  Console.Write('숫자 59의 이진수: ');  reverse(DecimalToBinary(num));  } } // 이 코드는 phasing17에서 제공한 것입니다.>
자바스크립트
>
파이썬3
# Python3 program to implement the above approach # function to convert the decimal number # to binary number def DecimalToBinary(num): strs = '' while num: # if (num & 1) = 1 if (num & 1): strs += '1' # if (num & 1) = 0 else: strs += '0' # right shift by 1 num>>= 1 return strs # 문자열을 뒤집는 함수 def reverse(strs): print(strs[::-1]) # 드라이버 코드 num = 59 print('Binary of num 59 is:', end=' ') reverse(DecimalToBinary(num)) # 이 코드는 phasing17에 의해 기여되었습니다.>

산출
Binary of num 59 is: 111011>

시간 복잡도: O(로그 n) & 보조 공간: 오(1)

배열을 사용하지 않고도 10진수를 2진수로 변환할 수 있습니다.

C++
// C++ implementation of the approach #include  #include  using namespace std; #define ull unsigned long long int // Function to return the binary // equivalent of decimal value N int decimalToBinary(int N) {  // To store the binary number  ull B_Number = 0;  int cnt = 0;  while (N != 0) {  int rem = N % 2;  ull c = pow(10, cnt);  B_Number += rem * c;  N /= 2;  // Count used to store exponent value  cnt++;  }  return B_Number; } // Driver code int main() {  int N = 17;  cout << decimalToBinary(N);  return 0; } // This code is contributed by Sania Kumari Gupta (kriSania804)>
// C implementation of the approach #include  #include  #define ull unsigned long long int // Function to return the binary // equivalent of decimal value N int decimalToBinary(int N) {  // To store the binary number  ull B_Number = 0;  int cnt = 0;  while (N != 0) {  int rem = N % 2;  ull c = pow(10, cnt);  B_Number += rem * c;  N /= 2;  // Count used to store exponent value  cnt++;  }  return B_Number; } // Driver code int main() {  int N = 17;  printf('%u', decimalToBinary(N));  return 0; } // This code is contributed by Sania Kumari Gupta (kriSania804)>
자바
// Java implementation of the approach  import java.io.*; class GFG  { // Function to return the binary  // equivalent of decimal value N  static int decimalToBinary(int N)  {   // To store the binary number   int B_Number = 0;   int cnt = 0;   while (N != 0)  {   int rem = N % 2;   double c = Math.pow(10, cnt);   B_Number += rem * c;   N /= 2;   // Count used to store exponent value   cnt++;   }   return B_Number;  }  // Driver code  public static void main (String[] args) {    int N = 17;   System.out.println (decimalToBinary(N));  } } // This code is contributed by ajit.>
씨#
// C# implementation of the approach using System; class GFG {   // Function to return the binary  // equivalent of decimal value N  static int decimalToBinary(int N)  {   // To store the binary number   int B_Number = 0;   int cnt = 0;   while (N != 0)  {   int rem = N % 2;   int c = (int)Math.Pow(10, cnt);   B_Number += rem * c;   N /= 2;   // Count used to store exponent value   cnt++;   }   return B_Number;  }  // Driver code  static public void Main () {  int N = 17;   Console.Write(decimalToBinary(N));  } } // This code is contributed by Tushil.>
자바스크립트
>
파이썬3
# Python3 implementation of the approach  # Function to return the binary  # equivalent of decimal value N  def decimalToBinary(N): # To store the binary number  B_Number = 0 cnt = 0 while (N != 0): rem = N % 2 c = pow(10, cnt) B_Number += rem * c N //= 2 # Count used to store exponent value  cnt += 1 return B_Number # Driver code  N = 17 print(decimalToBinary(N)) # This code is contributed by  # SHUBHAMSINGH10>

산출
10001>

시간 복잡도: 오(로그인) & 보조 공간: 오(1)

이 방법은 이 문서에서 설명한 대로 이진수를 십진수로 변환하는 방법과 유사합니다. 우편 .
10진수를 2진수 형식으로 변환하는 또 다른 방법이 있습니다. 아이디어는 사용하는 것입니다 비트셋 .

아래는 위의 접근 방식을 구현한 것입니다.

C++
//C++ program to convert a decimal number //to its binary form. //including header file #include  using namespace std; //Function to convert a decimal number //to its binary form string decimalToBinary(int n) {  //finding the binary form of the number and   //converting it to string.   string s = bitset<64>(n).to_string();    //'1'의 첫 번째 발생을 찾아서 //앞에 오는 0을 제거합니다.  const auto loc1 = s.find('1');    if(loc1 != 문자열::npos) return s.substr(loc1);    '0'을 반환합니다; } //드라이버 코드 int main() { int n = 17;    //함수 호출 cout<< decimalToBinary(n);  return 0; } //This code is contributed by yashbeersingh42>
자바
// Java program to convert a decimal number to its binary // form import java.util.*; class DecimalToBinary {  // Function to convert a decimal number to its binary  // form  public static String decimalToBinary(int n)  {  // Finding the binary form of the number and  // converting it to a string  String s = Integer.toBinaryString(n);  // Finding the first occurrence of '1' to strip off  // the leading zeroes  int loc1 = s.indexOf('1');  if (loc1 != -1) {  return s.substring(loc1);  }  return '0';  }  // Driver code  public static void main(String[] args)  {  int n = 17;  // Function call  System.out.println(decimalToBinary(n));  } } // This code is contributed by phasing17>
씨#
// C# program to convert a decimal number // to its binary form. using System; class HelloWorld {  // Function to convert a decimal number  // to its binary form  public static String decimalToBinary(int n)  {  // finding the binary form of the number and   //converting it to string.   String s = Convert.ToString(n, 2);  return s;  }  static void Main() {  int n = 17;  //Function call  Console.WriteLine(decimalToBinary(n));  } } // The code is contributed by Nidhi goel.>
자바스크립트
// Javascript program to convert a decimal number // to its binary form. // Function to convert a decimal number // to its binary form function decimalToBinary( n) {  // finding the binary form of the number and   // converting it to string.   const s = n.toString(2);    return s; } // Driver Code let n = 17; // Function call console.log(decimalToBinary(n));  // This code is contributed by imruhrbf8.>
파이썬3
# Python program to convert a decimal number # to its binary form. # Function to convert a decimal number # to its binary form def decimalToBinary( n): # finding the binary form of the number and  # converting it to string.  s = bin(n)[2:] # Finding the first occurrence of '1' # to strip off the leading zeroes. # const auto loc1 = s.find('1') loc1 = s[s.index('1'):] return loc1 return '0' # Driver Code n = 17 # Function call print(decimalToBinary(n))>

산출
10001>

시간 복잡도: 오(로그인) & 보조 공간: 오(1)

또 다른 접근법

C++
// C++ program to convert Decimal to Binary Number #include  using namespace std; int main() {  // input number  int number = 15;  int n = (int)(log2(number));    // binary output  // using the inbuilt function  cout << 'the binary number is : '  << bitset<64>(번호).to_string().substr(64 - n - 1); } // 이 코드는 phasing17에 의해 작성되었습니다.>
자바
//To convert Decimal to Binary Number// import java.util.*;  public class Main{  public static void main(String [] args){  //input//  int number =15;    //output//  System.out.println('the binary number is : '+ Integer.toString(number,2));    //This code is written by ZEESHAN AHMAD//  }  }>
씨#
// To convert Decimal to Binary Number// using System;  class GFG{  public static void Main(){  // input//  int number =15;    //output//  Console.WriteLine('the binary number is : '+ Convert.ToString(number, 2));  }  } // This code is contributed by code_hunt.>
자바스크립트
// JavaScript program to convert Decimal to Binary Number // input number var number = 15; // binary output // using the inbuilt function console.log('the binary number is :', number.toString(2)); // This code is written by phasing17>
파이썬3
# Python3 program to convert Decimal to Binary Number # input number number = 15 # binary output # using the inbuilt function print('the binary number is :', bin(number)[2::]) # This code is written by phasing17>

산출
the binary number is : 1111>

시간 복잡도: O(로그인) & 보조 공간: 오(1)