What value to use? C # (Adding numbers represented as strings)

If I have a string (010) and I want to add 1 to it (011), what type of value should I use to convert this string to a number to add and at the same time store an integer, not 10 + 1 = 11.

+3
source share
10 answers

You can use something like this:

string initialValue = "010";
int tempValue = Int.Parse(initialValue) + 1;
string newValue = tempValue.ToString("000");

You do your math as usual and then return your string to the previous format using the number formatting function .ToString()

+15
source
if (int.TryParse(str, out i))
    str = (i + 1).ToString("000");

NTN.

( edit : fixed issues noted by BoltBait and steffenj)

+5
source

, , (, visual studio). Convert() . 2 -2. , .

string s = "010";
s = Convert.ToString(Convert.ToInt32("010", 2) + 1, 2);
+3

, , int ( ). , ... , .

string ParseAndAdd(string text, int add)
{
    int parsed = int.Parse(text);
    return (parsed + add).ToString().PadLeft(text.Length, '0');
}
+1
int value = 10;// or, int value = Convert.ToInt32("010");
value += 1;
string text = value.ToString("000");

"000" ToString . .net, . "0" , , .

+1

- :

string a = "010";
string b = "1";
a = (int.Parse(a) + int.Parse(b)).ToString(new string('0', Math.Max(a.Length, b.Length)));
Console.WriteLine(a);

a b.

+1
string str = "110";
int i = 0;
int maxSize = 3;
if (int.TryParse(str, out i))
{
    str = string.Concat(new string('0', maxSize - (i + 1).ToString().Length), i + 1);
}
+1

:

    public string AddOne (string text)
    {
        int parsed = int.Parse(text);
        string formatString = "{0:D" + text.Length + "}";
        return string.Format(formatString, parsed + 1);
    }

, , , .

int.Parse. , , , (ArgumentException ArgumentNullException) int.Parse, , .

+1

, ?

, , , , ?

0

It looks like a binary string operation, I think you should create a class BinaryStringthat needs to have an internal binary decimal conversion, and then overload it +, -etc. And perform the decimal operation inside. and displays the result as a binary string.

0
source

Source: https://habr.com/ru/post/1698360/


All Articles