0

それは私に尋ねられたインタビューの質問でした-itoa組み込み関数を使用せずに変換を記述してください。

以下は私が使用しているアルゴリズムです。しかし('0' + n % 10);、エラーをスローしています:

文字列を 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);
}
4

3 に答える 3

0

('0' + n % 10)int値になるため、キャストして に戻す必要がありますchar-間違った側に符号を追加する、負の値を扱うなど、コードには他にもいくつかの問題があります。

私のバージョン:

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);
}
于 2013-10-28T01:33:18.717 に答える