Answer to Question #40115 in C++ for Asma

Question #40115
Write a C++ program that reads as a variable an integer containing only 0s and 1s (i.e., a binary integer) and returns its decimal equivalent.
Hint:
Use the remainder and division operators to pick off the binary number’s digits one at a time, from right to left. In the decimal number system, the rightmost digit has a positional value of 1 and the next digit to the left has a positional value of 10, then 100, then 1000, and so on.
The decimal number 234 can be interpreted as 4 * 1 + 3 * 10 + 2 * 100. In the binary number system, the rightmost digit has a positional value of 1, the next digit to the left has a positional valueof2,then4,then8,andsoon.Thedecimalequivalentofbinary1101is1*20 +0*21 +1 * 22 + 1 * 23, or 1 + 0 + 4 + 8 or, 13.
1
Expert's answer
2014-03-24T11:15:26-0400
#include <iostream>

using namespace std;

int main () {
long result = 0; // variable of result
int input; // input int 10...1
cin >> input; // reading input int
long power = 1; // power of 2 (1, 2, 4, ...)
while (input > 0) { // looking on input int
result += (input % 10) * power; // using remainder operator for taking last digit and multiplying it on power of 2
input = (int) input / 10; // using division operator for deleting last digit
power *= 2; // increasing power of 2
}
cout << result; // output of result
return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS