Skip to content

Commit 5633cd9

Browse files
committed
Sync LeetCode submission Runtime - 0 ms (100.00%), Memory - 17.6 MB (97.35%)
1 parent 71b301b commit 5633cd9

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
<p>Alice and Bob are playing a game. Initially, Alice has a string <code>word = &quot;a&quot;</code>.</p>
2+
3+
<p>You are given a <strong>positive</strong> integer <code>k</code>.</p>
4+
5+
<p>Now Bob will ask Alice to perform the following operation <strong>forever</strong>:</p>
6+
7+
<ul>
8+
<li>Generate a new string by <strong>changing</strong> each character in <code>word</code> to its <strong>next</strong> character in the English alphabet, and <strong>append</strong> it to the <em>original</em> <code>word</code>.</li>
9+
</ul>
10+
11+
<p>For example, performing the operation on <code>&quot;c&quot;</code> generates <code>&quot;cd&quot;</code> and performing the operation on <code>&quot;zb&quot;</code> generates <code>&quot;zbac&quot;</code>.</p>
12+
13+
<p>Return the value of the <code>k<sup>th</sup></code> character in <code>word</code>, after enough operations have been done for <code>word</code> to have <strong>at least</strong> <code>k</code> characters.</p>
14+
15+
<p>&nbsp;</p>
16+
<p><strong class="example">Example 1:</strong></p>
17+
18+
<div class="example-block">
19+
<p><strong>Input:</strong> <span class="example-io">k = 5</span></p>
20+
21+
<p><strong>Output:</strong> <span class="example-io">&quot;b&quot;</span></p>
22+
23+
<p><strong>Explanation:</strong></p>
24+
25+
<p>Initially, <code>word = &quot;a&quot;</code>. We need to do the operation three times:</p>
26+
27+
<ul>
28+
<li>Generated string is <code>&quot;b&quot;</code>, <code>word</code> becomes <code>&quot;ab&quot;</code>.</li>
29+
<li>Generated string is <code>&quot;bc&quot;</code>, <code>word</code> becomes <code>&quot;abbc&quot;</code>.</li>
30+
<li>Generated string is <code>&quot;bccd&quot;</code>, <code>word</code> becomes <code>&quot;abbcbccd&quot;</code>.</li>
31+
</ul>
32+
</div>
33+
34+
<p><strong class="example">Example 2:</strong></p>
35+
36+
<div class="example-block">
37+
<p><strong>Input:</strong> <span class="example-io">k = 10</span></p>
38+
39+
<p><strong>Output:</strong> <span class="example-io">&quot;c&quot;</span></p>
40+
</div>
41+
42+
<p>&nbsp;</p>
43+
<p><strong>Constraints:</strong></p>
44+
45+
<ul>
46+
<li><code>1 &lt;= k &lt;= 500</code></li>
47+
</ul>
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# Approach: Iteration
2+
3+
class Solution:
4+
def kthCharacter(self, k: int) -> str:
5+
ans = 0
6+
while k != 1:
7+
t = k.bit_length() - 1
8+
9+
if (1 << t) == k:
10+
t -= 1
11+
k -= 1 << t
12+
ans += 1
13+
14+
return chr(ord('a') + ans)
15+

0 commit comments

Comments
 (0)