Created
May 6, 2020 09:23
-
-
Save ertugrulozcan/f5dc8a74d2be9225a41e625aa871d412 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution | |
{ | |
public int Reverse(int number) | |
{ | |
try | |
{ | |
int[] digitArray = GetDigitArray(number); | |
return ConvertDigitArrayToInteger(digitArray.Reverse().ToArray()); | |
} | |
catch (OverflowException) | |
{ | |
return 0; | |
} | |
} | |
private static int[] GetDigitArray(int number) | |
{ | |
int digitCount = GetDigitCount(number); | |
int[] digitArray = new int[digitCount]; | |
int pivot = number; | |
for (int i = digitCount - 1; i >= 0; i--) | |
{ | |
int digit = GetLastDigit(pivot, out int left); | |
digitArray[i] = digit; | |
pivot = left; | |
} | |
return digitArray; | |
} | |
private static int GetLastDigit(int number, out int left) | |
{ | |
int lastDigit = number % 10; | |
left = (number - lastDigit) / 10; | |
return lastDigit; | |
} | |
private static int GetDigitCount(int number, int power = 0) | |
{ | |
number = Math.Abs(number); | |
if (number >= Math.Pow(10, power)) | |
return GetDigitCount(number, power + 1); | |
return power; | |
} | |
private static int ConvertDigitArrayToInteger(int[] array) | |
{ | |
int result = 0; | |
int digitCount = array.Length; | |
checked | |
{ | |
for (int i = 0; i < digitCount; i++) | |
{ | |
result += array[i] * (int)Math.Pow(10, digitCount - i - 1); | |
} | |
return result; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment