Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created July 4, 2017 22:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/8a3fd6e2cbe42543be16381e7cf561d8 to your computer and use it in GitHub Desktop.
Save jianminchen/8a3fd6e2cbe42543be16381e7cf561d8 to your computer and use it in GitHub Desktop.
Reverse an integer - do it yourself
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConvertIntToString
{
/// <summary>
/// July 4, 2017
/// </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)
{
var reversed = new List<int>();
if (n == 0)
{
return new char[] { '0' };
}
bool isNonNegative = n >= 0;
int unsignedInt = Math.Abs(n);
while (unsignedInt > 0)
{
int remain = unsignedInt % 10;
unsignedInt = unsignedInt / 10;
reversed.Add(remain);
}
var length = reversed.Count;
var newLength = isNonNegative? length: (length + 1);
var result = new char[newLength];
int start = 0;
if (!isNonNegative)
{
result[0] = '-';
start = 1;
}
for (int i = length - 1; i >= 0; i-- )
{
result[start++] = (char)('0' + reversed[i]);
}
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment