diff --git a/leetcode/2180. Count Integers With Even Digit Sum/README.md b/leetcode/2180. Count Integers With Even Digit Sum/README.md index 85502c76..29917c23 100644 --- a/leetcode/2180. Count Integers With Even Digit Sum/README.md +++ b/leetcode/2180. Count Integers With Even Digit Sum/README.md @@ -57,6 +57,37 @@ public: }; ``` +## Solution 2. Pattern Finding + +`num` | 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| +--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|-- +digit sum |1|2|3|4|5|6|7|8|9|1|2|3|4|5|6|7|8|9|10|2|3|4|5|6|7 +digit sum is even|0|1|0|1|0|1|0|1|0|0|1|0|1|0|1|0|1|0|0|1|0|1|0|1|0 +answer |0|1|1|2|2|3|3|4|4|4|5|5|6|6|7|7|8|8|9|10|10|11|11|12|12| + + +The answer increments when the digit sum of `num` is even. + +We can see that the answer is somewhat related to `num / 2` and `digitSum(num) % 2`. It turns out to be `(num - digitSum(num) % 2) / 2`. + +```cpp +// OJ: https://leetcode.com/problems/count-integers-with-even-digit-sum/ +// Author: github.com/lzl124631x +// Time: O(lgN) +// Space: O(1) +class Solution { +public: + int countEven(int num) { + int sum = 0, tmp = num; + while (num) { + sum += num % 10; + num /= 10; + } + return (tmp - sum % 2) / 2; + } +}; +``` + ## Discuss https://leetcode.com/problems/count-integers-with-even-digit-sum/discuss/1784735 \ No newline at end of file