Printing a number in reverse

Hi everyone. I was given an assignment to convert a decimal into a binary. Here is my code below, it has no errors. The only problem is that I can't seem to find a way to return the number in reverse. i.e when the user inputs 23, the output is 11101 instead of 10111. What should I add? Thanks.

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>
using namespace std;

void binary()
{
	int integer = 0;
	int remainder = 0;
	
	cout <<"Enter a positive integer: ";
	cin >> integer;
	
	
while(integer < 0)
{
	cout << "Not a positive integer, retry: ";
	cin >> integer;
	
}

while(integer!=0)
{


	remainder = integer % 2;
	cout << remainder;
	integer = integer/2;
}
		
}




int main()
{
	binary();
	return 0;
}
You can apply similar logic to how you did the binary case, but instead of using powers of 2 you'd use powers of 10.
if it's just printing a number in reverse that you're after (as your post header seems to suggest) then you could (a) std::to_string() the number and then (b) use an std::ostream_iterator<char> with std::reverse_copy to directly print this std::string to console with std::cout
http://coliru.stacked-crooked.com/a/286eeab4ebfa5ddf
+JayhawkZombie I tried doing that, but the problem was that I had to create another while loop, and when this new while loop is nested inside the previous while loop, it outputs the wrong values. When it's outside, then it doesn't read the value returned by the previous loop. Not sure if this is making any sense.
+gunnerfunner thanks for tryna help, but I haven't done iterators yet. I'm just a beginner c++ programmer.
Here is a more mathematical approach to base conversion:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# include <iostream>
# include <cmath>

int main (int, char **) {
  /* symbol table for place values. */
  static char constexpr sym[36] = {
    '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F',
    'G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V',
    'W','X','Y','Z'
  };

  /* Convert this value */
  unsigned const N = 12941;
  
  /* Output radix.   rx <= sizeof(sym) */
  static unsigned constexpr rx = 2;
  
  std::cout << N << " = ";
  for (int place = std::floor(std::log(N) / std::log(rx)); place >= 0; --place)
    std::cout << sym[static_cast<unsigned int>(N / std::pow(rx, place)) % rx];
  std::cout << "\n";
}

http://coliru.stacked-crooked.com/a/0a1ecef3c0285d0f

For binary numbers (any integral output base <= 10, base > 1) the lookup table can be removed. For binary only, see:
http://coliru.stacked-crooked.com/a/f570515554e986bb

Edit:
I should add that this is the same idea as yours: the difference is that it starts from the most-significant digit and works down in left-to-right order. The logarithms are just there to find the position of the MSB.

An alternative solution is to do the work on the way back up the call stack:
1
2
3
4
5
6
7
# include <iostream>
std::string to_binary(unsigned const N) 
{ return (N == 0)? "": (to_binary(N / 2) + (N % 2? "1": "0")); }

int main() {
  std::cout << 12941 << " = " << to_binary(12941) << '\n';
}

http://coliru.stacked-crooked.com/a/9588801f4c553846
Last edited on
@NeonNovel,

You are correctly extracting the digits, but you need some way of storing them so you can write them out in the correct order (after your while loop). The ways suggested are reconstructing a new integer from the powers of 10 (@JayHawkZombie), using a string as a container (@gunnerfunner) and using recursive function calls to build a string (@mbozzi, second approach). Here's a slightly inefficient modification to your code that simply stores the digits in a vector and then writes them back in reverse:
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
#include <iostream>
#include <vector>
using namespace std;

void binary()
{
   int integer = 0;
   int remainder = 0;
   
   cout <<"Enter a positive integer: ";
   cin >> integer;
   
   
   while ( integer < 0 )
   {
      cout << "Not a positive integer, retry: ";
      cin >> integer;
   }

   vector<int> digits;                      // <==== to hold the digits
   while ( integer != 0 )
   {
      remainder = integer % 2;
      digits.push_back( remainder );        // <==== store the digits
      integer = integer / 2;
   }
   for ( int i = digits.size() - 1; i >= 0; i-- ) cout << digits[i];        // <==== print the digits backward
   cout << endl;
}


int main()
{
   binary();   // <==== this isn't really a good idea; input the integer in main
}



Of the approaches, though, @mbozzi's recursive solution was so slick that I had a go at hybridising his two approaches for more general number bases (hope he doesn't mind!) I've only gone up to base 16 (hexadecimal), although you could obviously add more symbols to go higher.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>
using namespace std;

char symbol[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

string intToBase( int n, int base ) {  return n > 0 ? intToBase( n / base, base ) + symbol[n%base] : ""; }

int main()
{
   int n, base;
   cout << "Enter a positive integer: ";   cin >> n   ;
   cout << "Enter a base (2-16): "     ;   cin >> base;
   cout << n << " in base " << base << " is " << intToBase( n, base );
}


1
2
3
Enter a positive integer: 25
Enter a base (2-16): 2
25 in base 2 is 11001


1
2
3
Enter a positive integer: 255
Enter a base (2-16): 16
255 in base 16 is FF

I have to admit, I wasn't expecting this many solutions. Don't know how to thank you all. By the way, I found an alternative approach:

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
#include <iostream>
#include <sstream>
#include <string>

using namespace std;

  

int main()
{	
	int intNumber;
    string strNumber;
    char holder=' ';
     
     cout << "Enter the positive integer: ";
    cin>>intNumber;
    
    while (intNumber < 0)
    {
    	cout<<"Not a positive integer. retry: ";
    	cin >> intNumber;
	}
   
    while(intNumber!=0)
    {
        holder=intNumber%2+'0';
        strNumber=holder+strNumber;
        intNumber/=2;
    }
    cout<<strNumber << endl;
   
    return 0;

		
}


Thanks for your help everyone. Your solutions are straightforward and not difficult to understand.
Last edited on
Topic archived. No new replies allowed.