Tutorialspoint
Problem
Solution
Submissions

Decimal to Binary Number

Certification: Basic Level Accuracy: 50% Submissions: 4 Points: 10

Write a C++ program that converts a decimal (base-10) number to its binary (base-2) representation.

Example 1
  • Input: n = 10
  • Output: "1010"
  • Explanation:
    • Step 1: Initialize an empty string to store the binary representation.
    • Step 2: Repeatedly divide the decimal number by 2 and collect the remainders.
    • Step 3: The remainders, read from bottom to top, give the binary representation.
    • Step 4: For 10, the divisions and remainders are: 10÷2=5 remainder 0, 5÷2=2 remainder 1, 2÷2=1 remainder 0, 1÷2=0 remainder 1.
Example 2
  • Input: n = 23
  • Output: "10111"
  • Explanation:
    • Step 1: Initialize an empty string to store the binary representation.
    • Step 2: Repeatedly divide the decimal number by 2 and collect the remainders.
    • Step 3: The remainders, read from bottom to top, give the binary representation.
    • Step 4: For 23, the divisions and remainders are: 23÷2=11 remainder 1, 11÷2=5 remainder 1, 5÷2=2 remainder 1, 2÷2=1 remainder 0, 1÷2=0 remainder 1.
Constraints
  • 0 ≤ n ≤ 10^9
  • Input is a non-negative integer
  • Time Complexity: O(log n)
  • Space Complexity: O(log n)
Control StructuresFunctions / MethodsCapgeminiSamsung
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use the division and remainder method: repeatedly divide by 2 and collect the remainders
  • The binary digits should be read in reverse order
  • Handle the special case of input 0 separately
  • Consider using a string to build the binary representation

Steps to solve by this approach:

 Step 1: Define a function decimal_to_binary that takes an integer n.

 Step 2: Handle the special case: return "0" if n is 0.
 Step 3: Initialize an empty string to store the binary representation.
 Step 4: Use a while loop that continues until n becomes 0.
 Step 5: For each iteration, add the character representation of n % 2 to the string.
 Step 6: Update n by dividing it by 2.
 Step 7: Reverse the resulting string to get the correct binary representation.
 Step 8: Return the final binary string.

Submitted Code :