Home > Blockchain >  Revers went wrong and returns the same number
Revers went wrong and returns the same number

Time:09-27

I think i cant understand something in the logic of my cycles, cant u match my mistake? We need to reverse the number. My code:

#include <iostream>
#include <string>

using namespace std;

int main(){
  string a;
  char b;
  cin >> a;
  for (int i = 0; i < a.size(); i  ){
    for (int j = a.size(); j > 0; j--){
      b = a[i];
      a[i] = a[j];
      a[j] = b;
      break;
    }
  }
  cout << a;
}

        

CodePudding user response:

The problem is your nested loop do the swap operation too many times(n*n times).

You just need a single loop to achieve that.

And also remind you the j should be a.size() - 1 and j >= 0, because the array index is start with 0.

#include <iostream>

int main()
{
    std::string a;
    char b;
    std::cin >> a;
    for(std::string::size_type i = 0; i < a.size() / 2;   i)
    {
        b = a[i];
        a[i] = a[a.size() - 1 - i];
        a[a.size() - 1 - i] = b;

    }
    std::cout << a << "\n";
}

You can consider a even more readable one.

#include <iostream>
#include <algorithm>

int main()
{
    std::string a;
    std::cin >> a;
    std::reverse(std::begin(a), std::end(a));
    std::cout << a << "\n";
}

CodePudding user response:

These nested for loops

  for (int i = 0; i < a.size(); i  ){
    for (int j = a.size(); j > 0; j--){
      b = a[i];
      a[i] = a[j];
      a[j] = b;
      break;
    }
  }

do not make sense.

For example the inner for loop has only one iteration due to the break statement within it. And this assignment

a[j] = b;

invokes undefined behavior because it is equivalent to

a[a.size()] = b;

It is enough to use only one for loop as for example

for ( std::string::size_type i = 0, n = a.size(); i < n / 2; i   )
{
    std::swap( a[i], a[n-i-1] );
}

If you do not know yet the standard function std::swap then you can rewrite the body of the for loop the following way

for ( std::string::size_type i = 0, n = a.size(); i < n / 2; i   )
{
    auto c = a[i];
    a[i] = a[n-i-1];
    a[n-i-1] = c; 
}
  • Related