Given an integer, please reverse its digits to obtain a new number. The new number should also follow the common form of integers, meaning that unless the original number is zero, the highest digit of the new number should not be zero after reversing.
Sample Inputs/Outputs
Sample Input(s) | Sample Output(s) |
---|---|
EOF inputs: each input consists of one line containing an integer, N. | The output consists of one line containing an integer, representing the reversed number. |
123 -380 | 321 -83 |
Thought Process
When receiving N, use an integer type to collect the data and check if N is negative. Set a boolean variable to store whether it is negative. If N is negative, multiply it by -1 to make N positive.
After converting N to a string, reverse it, and then convert it back to an integer type. If N was determined to be negative, multiply it by -1.
Sample Code-ZeroJudge A307: Flipping Numbers
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
cin.sync_with_stdio(0);
cin.tie(0);
int N;
while (cin >> N)
{
int negative = 1;
if (N < 0)
{
negative = -1;
N *= -1;
}
string str = to_string(N);
reverse(str.begin(), str.end());
int ans;
if (str.length() == 1) ans = int(str[0] - '0');
else ans = stoi(str);
ans *= negative;
cout << ans << "\n";
}
}
//ZeroJudge A307
//Dr. SeanXD