Looking into some programming task is sometimes challenging. You may think that the answer is quite simple, but actually someone has decided to make you sweat. In this task you should read one line from the console and print the sum and the count of all even positions. Quite trivial… Or so I thought.
After spending some 5 minutes (literally 5) I was able to come up with a solution, which was rather dissatisfying:
My solution worked only at 60% of the tests. At first I thought that I am missing something, so I spent some minutes more, looking into the task. I tried with Big Integers, but the result was the same. Finally I assumed, that if the first given digit is “0”, I miss it, when I convert to int. So, I tried and I have received 70 points. Still, not good. After thinking about another 20 minutes, I finally decided to take a look at the tests, which are give run-time error. And these tests had letters in them… So, I could not use my code and I had to re-write it (in the initial code I have assumed that we get only integers, so the cast to integer was breaking it). Finally this is what I get:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Program { static void Main() { string strInput = Console.ReadLine(); long sumEven = 0; long countEven = 0; for (int i = 0; i < strInput.Length; i++) { if (i % 2 != 1) { switch (strInput[i]) { case '0': sumEven += 0; countEven++; break; case '1': sumEven += 1; countEven++; break; case '2': sumEven += 2; countEven++; break; case '3': sumEven += 3; countEven++; break; case '4': sumEven += 4; countEven++; break; case '5': sumEven += 5; countEven++; break; case '6': sumEven += 6; countEven++; break; case '7': sumEven += 7; countEven++; break; case '8': sumEven += 8; countEven++; break; case '9': sumEven += 9; countEven++; break; } } } Console.WriteLine("{0} {1}", countEven, sumEven); } } |
Not as quick and not as neat as I wanted, but it still works!