If an array is having integers/Char/special Char… Ex: "**PST456DA85M2A!!23++46**", find out the sum of integers.

Note: If we find consecutive digits in array we need to treat it as number, let say 456, we need to treat it as [ four hundred and fifty six]. Write a program to get the output by summing 456+85+2+23+46.

Also this needs to be done in less number of iterations.

Solution

string inputString = "PST456DA85M2A!!23++4600"; char[] inputChars = inputString.ToCharArray(); double sum = 0; double tempnum = 0; double powerCounter = 0; double num; for (int i = inputChars.Length - 1; i >= 0; i--) { if (inputChars[i] >= 48 && inputChars[i] <= 57) { num = inputChars[i] - 48; tempnum = num * Math.Pow(10, powerCounter) + tempnum; powerCounter = powerCounter + 1; } else { sum = sum + tempnum; powerCounter = 0; tempnum = 0; } } Console.WriteLine(); Console.WriteLine(inputString); Console.WriteLine(sum); Console.ReadLine();

No Comments

Filed under:
Number