-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountIntegersWithEvenDigitSum.php
More file actions
56 lines (53 loc) · 1.27 KB
/
Copy pathCountIntegersWithEvenDigitSum.php
File metadata and controls
56 lines (53 loc) · 1.27 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php
namespace App;
/**
* Count Integers With Even Digit Sum
*
* Given a positive integer num, return the number of positive integers less than or equal to num whose digit sums are
* even. The digit sum of a positive integer is the sum of all its digits.
*
* Example 1:
* Input: num = 4
* Output: 2
* Explanation:
* The only integers less than or equal to 4 whose digit sums are even are 2 and 4.
*
* Example 2:
* Input: num = 30
* Output: 14
* Explanation:
* The 14 integers less than or equal to 30 whose digit sums are even are
* 2, 4, 6, 8, 11, 13, 15, 17, 19, 20, 22, 24, 26, and 28.
*
* https://leetcode.com/problems/count-integers-with-even-digit-sum
*/
class CountIntegersWithEvenDigitSum
{
/**
* @param int $num
* @return int
*/
public function countEven(int $num): int
{
$count = 0;
for ($i = 1; $i <= $num; $i++) {
if ($this->isEvenDigitSum($i)) {
$count++;
}
}
return $count;
}
/**
* @param int $num
* @return bool
*/
private function isEvenDigitSum(int $num): bool
{
$sum = 0;
while ($num > 0) {
$sum += $num % 10;
$num = (int)($num / 10);
}
return $sum % 2 === 0;
}
}