Convert Decimal to Binary

Convert Decimal to Binary

Hard C++ Control Flow 33 views
Explanation Complexity

Problem Statement

Convert decimal number to binary (base 2) representation.
Real Life: How computers store all data internally.

Input Format

A positive integer N (decimal number).

Output Format

Binary (base-2) representation of the number.

Example

10
1010

Constraints

• N ≥ 0

• Use integer arithmetic

Concept Explanation

Computers store all data in binary (0 and 1).
Decimal to binary conversion is done by repeated division by 2.

Step-by-Step Explanation

1.Take the decimal number N.

2.If N is 0, binary is 0.

3.While N > 0:

• Find remainder N % 2 (this gives a binary digit).

• Store the remainder.

• Divide N by 2.

4.The remainders are obtained in reverse order.

5.Print the stored remainders from last to first to get binary number.

Concept Explanation

Computers store all data in binary (0 and 1).
Decimal to binary conversion is done by repeated division by 2.

Step-by-Step Explanation

1.Take the decimal number N.

2.If N is 0, binary is 0.

3.While N > 0:

• Find remainder N % 2 (this gives a binary digit).

• Store the remainder.

• Divide N by 2.

4.The remainders are obtained in reverse order.

5.Print the stored remainders from last to first to get binary number.

Input / Output Format

Input Format
A positive integer N (decimal number).
Output Format
Binary (base-2) representation of the number.
Constraints
• N ≥ 0

• Use integer arithmetic

Examples

Input:
10
Output:
1010

Example Solution (Public)

C++
void control_q14_decimal_to_binary() {
    int decimal = 25;
    int binary[32];
    int index = 0;
    
    int temp = decimal;
    while(temp > 0) {
        binary[index] = temp % 2;
        temp = temp / 2;
        index++;
    }
    
    cout << "Decimal " << decimal << " in binary: ";
    for(int i = index - 1; i >= 0; i--) {
        cout << binary[i];
    }
    cout << endl;
}

Official Solution Code

void control_q14_decimal_to_binary() {
    int decimal = 25;
    int binary[32];
    int index = 0;
    
    int temp = decimal;
    while(temp > 0) {
        binary[index] = temp % 2;
        temp = temp / 2;
        index++;
    }
    
    cout << "Decimal " << decimal << " in binary: ";
    for(int i = index - 1; i >= 0; i--) {
        cout << binary[i];
    }
    cout << endl;
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.