Given a decimal number N, compute its binary equivalent.
Input: N = 7
Output: 111
Input: N = 33
Output: 100001
Input: N = 0
Output: 0
The binary representation of a decimal number is obtained by repeatedly dividing the number by 2 and collecting the remainders in reverse order.
#include <iostream>
#include <string>
class Solution {
public:
void decimalToBinary(int N) {
if (N == 0) {
std::cout << "0";
return;
}
std::string binary = "";
while (N > 0) {
int rem = N % 2;
binary = std::to_string(rem) + binary;
N = N / 2;
}
std::cout << binary;
}
};
class Solution {
public void decimalToBinary(int N) {
if (N == 0) {
System.out.print("0");
return;
}
StringBuilder binary = new StringBuilder();
while (N > 0) {
int rem = N % 2;
binary.insert(0, rem);
N = N / 2;
}
System.out.print(binary.toString());
}
}
class Solution:
def decimal_to_binary(self, N):
if N == 0:
print("0")
return
binary = ""
while N > 0:
rem = N % 2
binary = str(rem) + binary
N = N // 2
print(binary)
class Solution {
decimalToBinary(N) {
if (N === 0) {
console.log("0");
return;
}
let binary = "";
while (N > 0) {
let rem = N % 2;
binary = rem.toString() + binary;
N = Math.floor(N / 2);
}
console.log(binary);
}
}
Time Complexity: O(log N), as the loop runs for the number of bits in N.
Space Complexity: O(log N), for storing the binary string of length log₂(N).
Your notes are automatically saved in your browser's local storage and will persist across sessions on this device.