This program should show that the input is equal to the inverse number

Viewed 77

#include <iostream>
using namespace std;

int main() {
    int n;
    int reversedNumber = 0;
    int remainder;

    cout << "Enter an integer: ";
    cin >> n;

    while (n != 0) {
        remainder = n % 10;
        reversedNumber = (reversedNumber * 10) + remainder;
        n /= 10;
    }
    if (reversedNumber == n)
        cout << "YES";
    else
        cout << "NO";
    return 0;
}

Hello, I want the compiler to show yes but when i enter 2356532 in my input shows No ,This program should show that the input is equal to the inverse number.`

2 Answers

You divide n /= 10 in your loop until you have 0 left so if (reversedNumber == n) will never be true for anything but 0 as input.

Save n before the loop and compare with the value you've saved after the loop.

Example:

int saved = n;
while (n != 0) {
    remainder = n % 10;
    reversedNumber = (reversedNumber * 10) + remainder;
    n /= 10;
}
if (reversedNumber == saved) ...

Demo

You are clearly updating the value of n inside the while loop. At the end, its value will always be 0. Hence, your if statement will always return false.
I suggest you save the initial value of n in a new variable after getting user input and make the comparison between the reversedNumber and that value.

Related