This is my solution for the leetcode reverse int question:
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]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ArrayQuestions
{
/// <summary>
/// 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: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
/// </summary>
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
int temp = 1534236469;
int result = Reverse(temp);
Assert.AreEqual(0, result);
}
[TestMethod]
public void TestMethod2()
{
int temp = 123;
int result = Reverse(temp);
Assert.AreEqual(321, result);
}
public int Reverse(int x)
{
int result = 0;
bool negative = false;
if (x < 0)
{
negative = true;
x = -x;
}
int prevRevNum = 0;
while (x != 0)
{
int currentDigit = x % 10;
result = (result * 10) + currentDigit;
if ((result - currentDigit) / 10 != prevRevNum)
{
return 0;
}
prevRevNum = result;
x = x / 10;
}
if (negative)
{
return -result;
}
return result;
}
}
}
This is the output:
Runtime: 52 ms, faster than 62.65% of C# online submissions for Reverse Integer.
Can you please comment on how can I make this code run faster? I guess the modulo and division are the key factors of speed here.
System.Math.DivRem
for doing the division and modulo operations in one go. \$\endgroup\$ – user190892 Jan 26 '19 at 22:34