Reverse Integer Algorithm
The Reverse Integer Algorithm is a widely used programming technique to reverse the digits of an integer number. It is a fundamental algorithm used in various scenarios, including solving mathematical problems, practicing programming skills, or incorporating into more complex algorithms. The main idea behind this algorithm is to isolate the last digit of the input integer, concatenate it to the reversed number being constructed, and then remove that digit from the original number. This process is repeated until every digit has been removed from the input number and added to the reversed number in the opposite order.
The algorithm can be implemented in any programming language, and usually involves a loop or recursion to iterate through the digits of the input number. During each iteration, the last digit is obtained by calculating the modulus of the number by 10, which yields the remainder when the number is divided by 10. This digit is then added to the reversed number, which is multiplied by 10 to shift any existing digits one position to the left. After adding the new digit, the original number is divided by 10 (integer division), effectively discarding the last digit that was just processed. The loop or recursion continues until the original number becomes zero, at which point the reversed number has been fully constructed. The algorithm also handles negative numbers by simply applying the process to the absolute value of the number and then applying the negative sign to the reversed result.
class Solution {
public:
int reverse(int x) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
bool minus = false;
if (x < 0) {
x = -x;
minus = true;
}
int res = 0;
while (x) {
res *= 10;
res += x % 10;
x /= 10;
}
return minus ? (-res) : res;
}
};