generated from eyamenko/dotnet-template-repository
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem56.cs
More file actions
37 lines (34 loc) · 981 Bytes
/
Problem56.cs
File metadata and controls
37 lines (34 loc) · 981 Bytes
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
namespace LeetCode;
/// <summary>
/// <see href="https://leetcode.com/problems/reverse-integer/">Reverse Integer</see>.
/// </summary>
public static class Problem56
{
/// <summary>
/// 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.
/// Time complexity: O(n).
/// Space complexity: O(1).
/// </summary>
/// <param name="x">Integer to reverse.</param>
/// <returns>Reversed integer.</returns>
public static int Reverse(int x)
{
var reversed = 0;
for (; x != 0; x /= 10)
{
try
{
checked
{
reversed *= 10;
reversed += x % 10;
}
}
catch (OverflowException)
{
return 0;
}
}
return reversed;
}
}