-
Description Replaced the Where(char.IsDigit) with Math.Abs() for negatives
Changed from query format to method format
You can convert each digit to a number in .Sum(), no need to use select
Instead of using char.GetNumericValue(), you can avoid casting back to int by subtracting the char by 48, the ASCII value of '0', which will return an int
Code using System; using System.Linq; using System.Collections.Generic; namespace Kumite { public class Problem { public static int SumDigitsOf(long integer) => Math.Abs(integer) .ToString() .Sum(x => x-48); } }
Test Cases namespace TestCases { using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; [TestFixture] public class SolutionTests { readonly Dictionary<long, int> expected = new Dictionary<long, int> { { 234, 9 }, { 366, 15 }, { -741, 12 }, { 2021, 5 }, { 1998, 27 }, { 1882, 19 }, { -1492, 16 }, { 999999999, 81 }, { 12345678901234, 55 }, { 99999999999999, 126 } }; [Test] public void TestForProblemDescription() { Assert.AreEqual(6, Kumite.Problem.SumDigitsOf(10023)); } [Test] public void Test10Samples() { foreach (var pair in expected) { Assert.AreEqual(pair.Value, Kumite.Problem.SumDigitsOf(pair.Key)); } } } }
Output:
-
Code - using System;
- using System.Linq;
- using System.Collections.Generic;
- namespace Kumite
- {
- public class Problem
- {
public static int SumDigitsOf(long integer) => (int)(from ch in integer.ToString()where Char.IsDigit(ch)select Char.GetNumericValue(ch)).Sum();- public static int SumDigitsOf(long integer) =>
- Math.Abs(integer)
- .ToString()
- .Sum(x => x-48);
- }
- }
- All
- {{group.name}} ({{group.count}})
This comment has been reported as {{ abuseKindText }}.
Show
This comment has been hidden. You can view it now .
This comment can not be viewed.
- |
- Reply
- Edit
- View Solution
- Expand 1 Reply Expand {{ comments?.length }} replies
- Collapse
- Remove
- Remove comment & replies
- Report
{{ fetchSolutionsError }}