It was an interview question asked to me - write `itoa` conversion without using any builtin functions.

The following is the algorithm I am using. But `('0' + n % 10);` is throwing an error:

cannot convert string to int

``private static string itoa(int n){string result = string.Empty;char c;bool sign = n > 0 ? true : false;while (true){result = result + ('0' + n % 10); //'0'n = n / 10;if(n <= 0){break;}}if(sign){result = result + '-';}return strReverse(result);}``

As @minitech commented, we usually just use `ToString()` to do that in C#. If you really want to write the algorithm on your own, the following is an implementation:

``````public static partial class TestClass {
public static String itoa(int n, int radix) {
if(0==n)
return "0";

var index=10;
var buffer=new char[1+index];
var xlat="0123456789abcdefghijklmnopqrstuvwxyz";

for(int r=Math.Abs(n), q; r>0; r=q) {
q=Math.DivRem(r, radix, out r);
buffer[index-=1]=xlat[r];
}

if(n<0) {
buffer[index-=1]='-';
}

return new String(buffer, index, buffer.Length-index);
}

public static void TestMethod() {
Console.WriteLine("{0}", itoa(-0x12345678, 16));
}
}
``````

It works only for `int`. The range `int` is `-2147483648 to 2147483647`, the length in the string representation would be max to 11.

For the signature of `itoa` in C is `char * itoa(int n, char * buffer, int radix);`, but we don't need to pass the buffer in C#, we can allocate it locally.

The approach that add '0' to the remainder may not work when the radix is greater than `10`; if I recall correctly, `itoa` in C supports up to 36 based numbers, as this implementation is.

I'm unclear why you'd want to do this; just call ToString on your integer. You can specify whatever formatting you need with the various overloads.

`('0' + n % 10)` results in an `int` value, so you should cast it back to `char`. There are also several other issues with your code, like adding `-` sign on the wrong side, working with negative values, etc.

My version:

``````static string itoa(int n)
{
char[] result = new char[11]; // 11 = "-2147483648".Length
int index = result.Length;
bool sign = n < 0;

do
{
int digit = n % 10;
if(sign)
{
digit = -digit;
}
result[--index] = (char)('0' + digit);
n /= 10;
}
while(n != 0);

if(sign)
{
result[--index] = '-';
}

return new string(result, index, result.Length - index);
}
``````

Top