-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuestion3.c++
More file actions
56 lines (44 loc) · 1.27 KB
/
Question3.c++
File metadata and controls
56 lines (44 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Write a C++ program that takes a decimal number as input from the user and converts it
// to its binary representation. Additionally, explain the algorithm you used
// for the conversion and any potential limitations of representing decimal numbers in binary.
#include <iostream>
#include <vector>
// Function to convert decimal to binary
std::vector<int> decimalToBinary(int decimal)
{
std::vector<int> binary;
if (decimal == 0)
{
binary.push_back(0);
}
else
{
while (decimal > 0)
{
binary.push_back(decimal % 2);
decimal /= 2;
}
}
// Reverse the binary vector to get the correct binary representation
std::reverse(binary.begin(), binary.end());
return binary;
}
int main()
{
int decimal;
std::cout << "Enter a decimal number: ";
std::cin >> decimal;
if (decimal < 0)
{
std::cout << "Please enter a non-negative decimal number." << std::endl;
return 1; // Exit with an error code
}
std::vector<int> binary = decimalToBinary(decimal);
std::cout << "Binary representation: ";
for (int digit : binary)
{
std::cout << digit;
}
std::cout << std::endl;
return 0;
}