-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
84 lines (77 loc) · 1.8 KB
/
main.cpp
File metadata and controls
84 lines (77 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// Source: https://leetcode.com/problems/reverse-integer
// Title: Reverse Integer
// Difficulty: Medium
// Author: Mu Yang <http://muyang.pro>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Given a signed 32-bit integer `x`, return `x` with its digits reversed. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-2^31, 2^31 - 1]`, then return `0`.
//
// **Assume the environment does not allow you to store 64-bit integers (signed or unsigned).**
//
// **Example 1:**
//
// ```
// Input: x = 123
// Output: 321
// ```
//
// **Example 2:**
//
// ```
// Input: x = -123
// Output: -321
// ```
//
// **Example 3:**
//
// ```
// Input: x = 120
// Output: 21
// ```
//
// **Constraints:**
//
// - `-2^31 <= x <= 2^31 - 1`
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <climits>
#include <cstdint>
#include <cstdlib>
#include <string>
using namespace std;
// String
class Solution {
public:
int reverse(int x) {
int64_t xx = static_cast<int64_t>(x);
int64_t sign = (xx >= 0) ? 1 : -1;
string s = to_string(abs(xx));
std::reverse(s.begin(), s.end());
int64_t y = sign * stoll(s);
return (y > INT_MAX || y < INT_MIN) ? 0 : y;
}
};
// Integer Division
class Solution2 {
public:
int reverse(int x) {
int64_t y = 0;
while (x != 0) {
y = y * 10 + x % 10;
x /= 10;
}
return (y > INT_MAX || y < INT_MIN) ? 0 : y;
}
};
// Integer Division
class Solution3 {
public:
int reverse(int x) {
int64_t y = 0;
while (x != 0) {
if (y > INT_MAX / 10 || y < INT_MIN / 10) return 0; // out of range
y = y * 10 + x % 10;
x /= 10;
}
return y;
}
};