878928. Decimal to binary

Easy

Decimal to Binary

Slug: decimal-to-binary-1610434291--161808

Difficulty: Easy

Id: 878928

Topic Tags: CPP

Summary

The problem involves converting a given decimal number into its binary representation. This is a basic algorithmic problem that requires understanding of the concept of binary numbers and their conversion from decimal.

Detailed Explanation

To convert a decimal number to binary, we can use the fact that each digit in binary represents 2^0 (1) or 2^1 (2), and so on. We iterate through the given decimal number, for each digit:

  • If the current digit is less than 2, the corresponding binary bit will be a 0.
  • If the current digit is greater than or equal to 2, we take the remainder of the division by 2, which gives us the next binary bit. We then subtract this remainder from the decimal number and repeat the process until the decimal number becomes 0.

Here's a step-by-step breakdown:

  1. Initialize an empty string binary to store the resulting binary representation.
  2. Iterate through each digit of the given decimal number.
  3. For each digit, if it is less than 2, append '0' to binary.
  4. If the digit is greater than or equal to 2, calculate its remainder when divided by 2 and append this remainder (either 0 or 1) to binary. Then subtract this remainder from the decimal number.
  5. Repeat steps 3-4 until the decimal number becomes 0.
  6. Return the resulting binary representation stored in binary.

Time complexity: O(log n), where n is the given decimal number, as we are performing log(n) operations (division and subtraction). Space complexity: O(1), as we are using a constant amount of space to store the binary representation.

Optimized Solutions

Java

View on GeeksforGeeks
public String decimalToBinary(int n) {
    StringBuilder binary = new StringBuilder();
    while (n > 0) {
        int remainder = n % 2;
        n /= 2;
        binary.append(remainder == 0 ? '0' : '1');
    }
    return binary.toString();
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.