Reverse int
To reverse an integer in C++, you can follow these steps:
- Declare a variable to store the original integer and assign it a value.
- Declare another variable to store the reversed integer and initialize it to 0.
- Create a while loop that continues until the original integer becomes 0.
- Inside the loop, extract the last digit of the original integer using the modulo operator (%).
- Multiply the reversed integer by 10 and add the extracted digit to it.
- Divide the original integer by 10 to remove the last digit.
- Repeat steps 4 to 6 until the original integer becomes 0.
- The final value of the reversed integer will be stored in the second variable you declared.
Here's an example implementation:
#include <iostream>
using namespace std;
int main() {
int originalInteger, reversedInteger = 0;
cout << "Enter an integer: ";
cin >> originalInteger;
while (originalInteger != 0) {
int digit = originalInteger % 10;
reversedInteger = reversedInteger * 10 + digit;
originalInteger /= 10;
}
cout << "Reversed integer: " << reversedInteger << endl;
return 0;
}
This code prompts the user to enter an integer, then it reverses the integer and prints the result.