Need some help with HW

This is the question:
http://gyazo.com/b2ef477a7edade0fdd3a40ac084cd441

Now I have the binary numbers printed out in my code, but I don't know how I can covert them into to decimal, any suggestions or help would be appreciated!


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
#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
using namespace std;

int main()
{
    int numberOfDigits;
    int numberOfRows;
    char flag;

    do {

        cout << "How many digits?: ";
        cin >> numberOfDigits;
        numberOfRows = pow(2, numberOfDigits);

        cout << "Binary" << "        Dec" << endl;
        cout << "------" << "------- ----" <<endl;

        for(int i = 0; i < numberOfRows; i++) {
            for(int j = 0; j < numberOfDigits; j++) {

                if (((i % static_cast<int>(numberOfRows / pow(2, j))) < (numberOfRows / pow(2, j + 1))))
                    cout << setw(3) << 0;
                else
                    cout << setw(3) << 1;
            }
            cout << endl;
        }

        cout << "Enter n to quit or any other key to continue: ";
        cin >> flag;
    } while (flag != 'n' && flag != 'N');

    return 0;
}
I have another simple method for solving this.
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
    int number = 10;
    std::string num;
    if(number != 0) while(number != 0) {num += std::to_string(number%2); number /= 2;}
    std::reverse(num.begin(), num.end());
    std::cout << num << "\t" << std::stoi(num, 0 , 2);
}
Topic archived. No new replies allowed.