Created
December 13, 2017 23:14
-
-
Save jianminchen/4bc5520120b5b18a0bb8b936e866a913 to your computer and use it in GitHub Desktop.
Code review on Dec. 13, 2017, the original practice was on Oct. 13, 2013.
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 ConvertToString | |
{ | |
/// <summary> | |
/// code review: | |
/// API used: | |
/// new string(char[]) - construct a string using the input of char array | |
/// string.ToCharArray(index, length) - convert a string to char array | |
/// new char[] {'0'} - convert one char to char array | |
/// (char) (n + '0') - convert one digit to char | |
/// Do not use: | |
/// char[] numbers = new char[]{'1','2'}; | |
/// string numberString = numbers.ToString(); | |
/// </summary> | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
RunTestcase3(); | |
} | |
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> | |
/// Learn API ToString() | |
/// Dec. 13, 2017 | |
/// Read the question on stackoverflow.com | |
/// https://stackoverflow.com/questions/27125430/array-tostring-returning-system-char-c-sharp | |
/// | |
/// </summary> | |
public static void RunTestcase3() | |
{ | |
char[] numbers = new char[]{'1','2'}; | |
string numberString = numbers.ToString(); | |
// Figure out why the output is System.Char[] | |
Debug.Assert(numberString[0] == '1'); | |
} | |
/// <summary> | |
/// Dec. 13, 2017 | |
/// </summary> | |
/// <param name="n"></param> | |
/// <returns></returns> | |
public static char[] convertTostring(int n) | |
{ | |
if (n < 0) | |
{ | |
var s = convertTostring(-1 * n); | |
return ("-" + new string(s)).ToCharArray(0, s.Length + 1); | |
} | |
// base case | |
if (n < 10) | |
{ | |
var number = (char)(n + '0'); | |
return new char[]{number}; | |
} | |
var rightMost = n % 10; | |
var current = (char)(rightMost + '0'); | |
var next = n / 10; | |
var converted = new string(convertTostring(next)) + current.ToString(); | |
return converted.ToCharArray(0, converted.Length); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment