Created
July 4, 2017 22:44
-
-
Save jianminchen/21cf635fa018f12743db1de9ff83f883 to your computer and use it in GitHub Desktop.
Reverse integer - recursive solution
This file contains 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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace ConvertIntToString | |
{ | |
/// <summary> | |
/// July 4, 2017 | |
/// recursive solution | |
/// </summary> | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var result = convertToString(-324); | |
} | |
// Write a function that converts an int into its alpha-numeric equivalent represented | |
// as a null terminated string. The function should accept an int as input and return | |
// a string as output. For instance, calling the function with an int value of 324 would | |
// return a null terminated string containing "324". Ensure that your function checks for | |
// appropriate boundary conditions and edge cases. Assume you cannot use any standard | |
// libraries (for example, no itoa or sprintf). | |
// Convert an int to alpha-numeric string | |
// let me think about module function: | |
// 324 % 10 = 4, | |
// 324 / 10 = 32 | |
// go to next iteration | |
public static char[] convertToString(int n) | |
{ | |
// base case | |
if (n == 0) | |
{ | |
return new char[] { '0' }; | |
} | |
bool isNegative = n < 0; | |
var number = Math.Abs(n); | |
var rightMostDigit = number % 10; | |
var nextIteration = number / 10; | |
bool hasNext = nextIteration > 0; | |
var current = (char)('0' + rightMostDigit); | |
if (!hasNext) | |
{ | |
if (isNegative) | |
{ | |
return new char[]{'-', current}; | |
} | |
return new char[]{ current }; | |
} | |
var result = convertToString(nextIteration); | |
var converted = new char[result.Length + (isNegative? 2 : 1)]; | |
int start = 0; | |
if (isNegative) | |
{ | |
converted[0] = '-'; | |
start = 1; | |
} | |
for (int i = 0; i < result.Length; i++) | |
{ | |
converted[start + i] = result[i]; | |
} | |
converted[start + result.Length] = current; // reversed order | |
return converted; | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment