Skip to content

Commit 8920316

Browse files
committed
#2180: Count Integers With Even Digit Sum; solution & tests
1 parent cde6047 commit 8920316

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* 2180
3+
* Count Integers With Even Digit Sum
4+
**
5+
* Given a positive integer num,
6+
* return the number of positive integers less than or equal to num
7+
* whose digit sums are even.
8+
*
9+
* The digit sum of a positive integer is the sum of all its digits.
10+
*
11+
* Example 1:
12+
* Input: num = 4
13+
* Output: 2
14+
* Explanation:
15+
* The only integers less than or equal to 4
16+
* whose digit sums are even are 2 and 4.
17+
*
18+
* Example 2:
19+
* Input: num = 30
20+
* Output: 14
21+
* Explanation:
22+
* The 14 integers less than or equal to 30
23+
* whose digit sums are even are
24+
* 2, 4, 6, 8, 11, 13, 15, 17, 19, 20, 22, 24, 26, and 28.
25+
*
26+
* Constraints:
27+
* • 1 <= num <= 1000
28+
*
29+
* Hint 1:
30+
* Iterate through all integers from 1 to num.
31+
*
32+
* Hint 2:
33+
* For any integer,
34+
* extract the individual digits to compute their sum and check if it is even.
35+
**
36+
* https://leetcode.com/problems/count-integers-with-even-digit-sum/
37+
***/
38+
39+
namespace Problems;
40+
41+
public class CountIntegersWithEvenDigitSum
42+
{
43+
public int CountEven( int num )
44+
{
45+
int sum = num + ( num / 10 ) + ( num / 100 ) + ( num / 1000 );
46+
47+
return ( num - ( sum & 1 ) ) / 2;
48+
}
49+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
using NUnit.Framework;
2+
3+
using Problems;
4+
5+
public class CountIntegersWithEvenDigitSumTests
6+
{
7+
[TestCase( 4, ExpectedResult = 2 )]
8+
[TestCase( 30, ExpectedResult = 14 )]
9+
[TestCase( 38, ExpectedResult = 18 )]
10+
[TestCase( 63, ExpectedResult = 31 )]
11+
public int CountEvenTest( int num ) =>
12+
new CountIntegersWithEvenDigitSum().CountEven( num );
13+
}

0 commit comments

Comments
 (0)