0

We are converting base 10 to a number in a different base(B). I am having trouble with the void reverse function it will not reverse the order of the numbers.

 string convertToBaseB(int num, int b){
int digit;
stringstream answer;
string x="";
    while(num>0){
    digit=num%b;
    num/=b;
    answer<<digit;
}
    return answer.str();}

void reverse(int x[],int size){//reversing the 

for(int k=0; k<size/2; k++){
    int temp=x[k];
    x[k]=x[size-k-1];
    x[size-k-1]=temp;}
}
wjl
  • 7,519
  • 2
  • 32
  • 41
  • 1
    What's your input? What's your output? What's your expected output? How is the convertToBaseB(...) function relevant to the question you're asking? – K Mehta Apr 10 '15 at 01:12
  • the input is a number in base 10 form and it is supposed to convert to a new number with a different base...the void reverse function is supposed to swap the ordering of the ouput of the convert to base b definition... – Kira Thalacker Apr 10 '15 at 01:14
  • That still doesn't tell us what your input to reverse is... what's the value of x and size that you're passing in? – K Mehta Apr 10 '15 at 01:17
  • I can *almost* but not quite tell what you are asking. Asking your question in a very clear manner will answers help you. See http://stackoverflow.com/help/how-to-ask for more information. – wjl Apr 10 '15 at 01:17

2 Answers2

1

Your reverse function works fine. However it doesn't looks like C++ to me... In C++ I would have a vector and do:

std::vector<int> arr;
//... fill arr
std::swap_ranges(&arr[0], &arr[arr.size()/2], arr.rbegin());

If you want to stick with your for loop, at least use std::swap like this

void reverse(int x[],int size) { 
    for(int k=0; k<size/2; k++)
        std::swap(x[k], x[size-k-1]);
}
  • Why abuse `std::swap_ranges` that way when there is [`std::reverse`](http://en.cppreference.com/w/cpp/algorithm/reverse)? – Blastfurnace Apr 10 '15 at 04:56
0

Works for me:

#include <iostream>

using namespace std;

void reverse(int x[],int size)
{

  for(int k=0; k<size/2; k++)
  {
    int temp=x[k];
    x[k]=x[size-k-1];
    x[size-k-1]=temp;
  }
}

int main()
{
  const int sz = 9;
  int* digits;

  digits = new int[sz];

  for (int i=0; i < sz; ++i)
  {
    digits[i] = i;
  }

  reverse(digits, sz);

  for (int i=0; i < sz; ++i)
  {
    cout<<digits[i]<<" ";
  }
  cout<<endl;
}