How do I get the mirror of the first element of an array?

Viewed 260

I need to input numbers into an array, get the first number, mirror it, and then see if any other numbers in said array are the same as the mirror.

Example: 4 numbers, 123 321 111 and 200; the mirror of 123 is 321, so it should tell me "Yes", since there is 1 more element in the array that is the same as the mirror.

#include <iostream>
    
using namespace std;
    
int main()
{
    int n = 0, mirror, cnt = 0;
    int* v = new int[n];
    
    cout << "How many elements?\n";
    cin >> n;
    
    for(int i=0; i<n; i++)
        cin >> v[i];
    
    while(v[0] != 0){
        mirror = mirror * 10 + v[0] % 10;
        v[0] /= 10;
    }
    cout << mirror;
    for(int i=0; i<n; i++)
        if(v[i] == mirror && v[i] != v[0])
            cnt++;
    if(cnt >=1)
        cout << "Yes";
    else
        cout << "No";
    return 0;
}
2 Answers

There are two major problems in your code. First, you are attempting to allocate your v array before you know the user's input value of n; this can be fixed by moving the declaration/allocation of v to after the cin >> n; line.

Second, you never give the mirror variable an initial (zero) value, so it could start out as anything, which you then add the digits' values to in your while loop.

Here's a fixed version of your code, with comments on the changed lines:

#include <iostream>

using namespace std;

int main()
{
    int n = 0, mirror = 0, cnt = 0; // MUST initialize "mirror"

    cout << "How many elements?\n";
    cin >> n;
    int* v = new int[n]; // CAN ONLY allocate the array AFTER we have input the value of "n"

    for (int i = 0; i < n; i++)
        cin >> v[i];

    while (v[0] != 0) {
        mirror = mirror * 10 + v[0] % 10;
        v[0] /= 10;
    }
    cout << mirror;
    for (int i = 0; i < n; i++)
        if (v[i] == mirror && v[i] != v[0])
            cnt++;
    if (cnt >= 1)
        cout << "Yes";
    else
        cout << "No";

    delete[] v; // For good coding style, don't forget to deallocate the array!
    return 0;
}

Instead of swapping bytes in integers, why don't you convert each number to a C string using itoa() and then use strrev() to reverse the string? Then you can compare the strings with strcmp(). Lesser code, also more understandable and less error-prone.

Related