Question: C++. Write a function to transform a decimal number into a binary number. The function must receive a positive integer value as a parameter and

C++. Write a function to transform a decimal number into a binary number. The function must receive a positive integer value as a parameter and must return a string with the binary representation of the number.

Given the integer value 7, the return value of your function must be the string: 111

Iterative process to convert a decimal number to binary format:

  • Divide the number by 2; the remainder is the first digit of your binary number (least significant). Example: 7%2 = 1
  • Subtract the remainder from your number and divide what's left by 2. Example: (7 - (7%2))/2 = 3
  • Repeat and concatenate new digits to the front of the binary number. 3%2 = 1 --> 11

Hint: you can use the function to_string (string to_string (int val)) to transform an integer value into a string.

C++. Write a function to transform a decimal number into a binary

1 #include 4 using namespace std; 6 string dec2bin(int number) Insert your code here 11 int main() 13 unsigned int number; 14 string result; 15 cin number; 17 return e

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!