Created
December 14, 2017 01:12
-
-
Save jianminchen/4c7e39a3c73ef8295bf28922218f3993 to your computer and use it in GitHub Desktop.
Convert to string - iterative solution - with bugs using those API, I should write one without using so many APIs later.
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.Diagnostics; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace ConvertToStringIterative | |
{ | |
/// <summary> | |
/// code review on Dec. 13, 2017 | |
/// </summary> | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
RunTestcase1(); | |
RunTestcase2(); | |
} | |
public static void RunTestcase1() | |
{ | |
var result = convertToString(123); | |
Debug.Assert(result[0] == '1' && result[1] == '2' && result[2] == '3'); | |
} | |
public static void RunTestcase2() | |
{ | |
var result = convertToString(-123); | |
Debug.Assert(result[0] == '-' && result[1] == '1' && result[2] == '2' && result[3] == '3'); | |
} | |
/// <summary> | |
/// code review on Dec. 13, 2017 | |
/// API used: | |
/// string.Join(string delimiter, char[], start, index) - failed, it is string[] as second argument | |
/// new string(char[], start, length) - ok | |
/// string.ToCharArray(start, length) | |
/// | |
/// IEnumerable<char> IEnumerable.Reverse<char> | |
/// Inverts the order of the elements in a sequence | |
/// | |
/// Char[] IEnumerable<char>.ToArray<char>() | |
/// Creates an array from a System.Collections.Generic.IEnumerable<T> | |
/// </summary> | |
/// <param name="n"></param> | |
/// <returns></returns> | |
public static char[] convertToString(int n) | |
{ | |
var output = new char[100]; // maximum length of integer is less than 100 | |
// more edge case | |
bool isNegative = n < 0; | |
int index = 0; | |
int current = isNegative? -n : n; | |
while(true) | |
{ | |
// base case | |
if (current < 10) | |
{ | |
output[index] = (char)(current + '0'); | |
index++; | |
break; | |
} | |
int rightMost = current % 10; | |
output[index] = (char) (rightMost + '0'); | |
current = current / 10; | |
index++; | |
} | |
// reverse the order | |
int length = isNegative ? (index + 1) : index; | |
var converted = new string(output, 0, index); | |
var reversed = converted.Reverse().ToString(); | |
reversed = isNegative ? ("-" + reversed) : reversed; | |
return reversed.ToArray(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment