An integer is processed from the least significant digit to the most significant. One digit is calculated modulo 10 (% 10), which is then added to the value of the character '0'. This results in one of the characters '0', '1', ..., '9'.
The numbers are pushed onto the stack because they must be presented in reverse order as they are processed (the most significant digit to the least significant digit). Doing this rather than re-adding numbers to a string may be more efficient, but since the number of digits is pretty low, you will need to run a test to be sure.
Processing non-positive numbers requires some additional processing.
public string IntToString(int a) { if (a == 0) return "0"; if (a == int.MinValue) return "-2147483648"; var isNegative = false; if (a < 0) { a = -a; isNegative = true; } var stack = new Stack<char>(); while (a != 0) { var c = a%10 + '0'; stack.Push((char) c); a /= 10; } if (isNegative) stack.Push('-'); return new string(stack.ToArray()); }
My first version used StringBuilder to create a string from an array of characters, but to get the string "out of" StringBuilder need to call a method called ToString . Obviously, this method does not do any int conversion for the conversion, which for me is the question in question.
But to prove that you can create a string without calling ToString , I switched to using the string constructor, which I would also suggest more efficient than using StringBuilder .
And if ToString in any form is forbidden, you cannot use string concatenation, as shown in the documentation for string.Concat :
The method combines arg0 and arg1, invoking the inconspicuous ToString method arg0 and arg1; it does not add delimiters.
therefore doing s += '1' will call '1'.ToString() . But for me it doesn’t matter. The important part is how you convert int to string.
Martin Liversage Jul 10 '13 at 16:05 2013-07-10 16:05
source share