LeetCode Algorithm 0007 - Reverse Integer (Easy)
Problem Link: https://leetcode.com/problems/reverse-integer/description/
Description
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [ − 2 31 , 2 31 − 1 ] [-2^{31}, 2^{31} - 1] [−231,231−1] . For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Solution C++
#pragma once
#include "pch.h"
// Problem: https://leetcode.com/problems/reverse-integer/description/
namespace P7ReverseInteger
{
class Solution
{
public:
int reverse(int x)
{
#if true // 使用 string
string s = x < 0 ? to_string(-x) : to_string(x);
std::reverse(s.begin(), s.end());
long long result = x < 0 ? -stoll(s) : stoll(s);
if (result > numeric_limits<int>::max() || result < numeric_limits<int>::min())
{
return 0;
}
return (int)result;
#endif
#if false // 使用 number: 网站答案的源码: Pop and Push Digits & Check before Overflow
int rev = 0;
while (x != 0)
{
int pop = x % 10;
x /= 10;
if (rev > INT_MAX / 10 || (rev == INT_MAX / 10 && pop > 7)) return 0;
if (rev < INT_MIN / 10 || (rev == INT_MIN / 10 && pop < -8)) return 0;
rev = rev * 10 + pop;
}
return rev;
#endif
}
};
}