How do I convert an Int to a String in C# without using ToString()?

前端 未结 10 1286
耶瑟儿~
耶瑟儿~ 2020-12-12 13:49

Convert the following int argument into a string without using any native toString functionality.

public string integerToString(int integerPas         


        
10条回答
  •  旧时难觅i
    2020-12-12 14:31

    Aiming for a shorter version, and one that uses Math.DivRem:

    string IntToString(int a)
    {
        if (a == int.MinValue)
            return "-2147483648";
        if (a < 0)
            return "-" + IntToString(-a);
        if (a == 0)
            return "0";
        var s = "";
        do
        {
            int r;
            a = Math.DivRem(a, 10, out r);
            s = new string((char)(r + (int)'0'), 1) + s;
        }
        while (a > 0);
        return s;
    }
    

    The use of the new string(..., 1) constructor is just a way to satisfy the OP's requirement that ToString not be called on anything.

提交回复
热议问题