Skip to content

Commit 1c3b858

Browse files
committed
Sync LeetCode submission Runtime - 3 ms (20.66%), Memory - 17.7 MB (71.93%)
1 parent da4044d commit 1c3b858

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

2050-count-good-numbers/README.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<p>A digit string is <strong>good</strong> if the digits <strong>(0-indexed)</strong> at <strong>even</strong> indices are <strong>even</strong> and the digits at <strong>odd</strong> indices are <strong>prime</strong> (<code>2</code>, <code>3</code>, <code>5</code>, or <code>7</code>).</p>
2+
3+
<ul>
4+
<li>For example, <code>&quot;2582&quot;</code> is good because the digits (<code>2</code> and <code>8</code>) at even positions are even and the digits (<code>5</code> and <code>2</code>) at odd positions are prime. However, <code>&quot;3245&quot;</code> is <strong>not</strong> good because <code>3</code> is at an even index but is not even.</li>
5+
</ul>
6+
7+
<p>Given an integer <code>n</code>, return <em>the <strong>total</strong> number of good digit strings of length </em><code>n</code>. Since the answer may be large, <strong>return it modulo </strong><code>10<sup>9</sup> + 7</code>.</p>
8+
9+
<p>A <strong>digit string</strong> is a string consisting of digits <code>0</code> through <code>9</code> that may contain leading zeros.</p>
10+
11+
<p>&nbsp;</p>
12+
<p><strong class="example">Example 1:</strong></p>
13+
14+
<pre>
15+
<strong>Input:</strong> n = 1
16+
<strong>Output:</strong> 5
17+
<strong>Explanation:</strong> The good numbers of length 1 are &quot;0&quot;, &quot;2&quot;, &quot;4&quot;, &quot;6&quot;, &quot;8&quot;.
18+
</pre>
19+
20+
<p><strong class="example">Example 2:</strong></p>
21+
22+
<pre>
23+
<strong>Input:</strong> n = 4
24+
<strong>Output:</strong> 400
25+
</pre>
26+
27+
<p><strong class="example">Example 3:</strong></p>
28+
29+
<pre>
30+
<strong>Input:</strong> n = 50
31+
<strong>Output:</strong> 564908303
32+
</pre>
33+
34+
<p>&nbsp;</p>
35+
<p><strong>Constraints:</strong></p>
36+
37+
<ul>
38+
<li><code>1 &lt;= n &lt;= 10<sup>15</sup></code></li>
39+
</ul>

2050-count-good-numbers/solution.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Approach 1: Fast Exponentiation
2+
3+
# Time: O(log n)
4+
# Space: O(1)
5+
6+
class Solution:
7+
def countGoodNumbers(self, n: int) -> int:
8+
mod = 10 ** 9 + 7
9+
10+
# Calculate x ^ y % mod
11+
def quick_mul(x, y):
12+
ret, mul = 1, x
13+
while y > 0:
14+
if y % 2 == 1:
15+
ret = ret * mul % mod
16+
mul = mul * mul % mod
17+
y //= 2
18+
return ret
19+
20+
return quick_mul(5, (n + 1) // 2) * quick_mul(4, n // 2) % mod
21+

0 commit comments

Comments
 (0)