Find The K-th Lucky Number — LeetCode 2802 Python Solution
MediumLeetCode PremiumBit ManipulationMathString
- Problem
- #2802
- Pattern
- Bit Manipulation
- Reading time
- 3 min
- Source
- leetcode.com
The problem
We know that 4 and 7 are lucky digits. Also, a number is called lucky if it contains only lucky digits.
Example
- Input
- k = 4
- Output
- "47"
- Explanation
- The first lucky number is 4, the second one is 7, the third one is 44 and the fourth one is 47.
Python solution
Python
class Solution:
def kthLuckyNumber(self, k: int) -> str:
n = 1
while k > 1 << n:
k -= 1 << n
n += 1
ans = []
while n:
n -= 1
if k <= 1 << n:
ans.append("4")
else:
ans.append("7")
k -= 1 << n
return "".join(ans)Complexity
| Measure | Complexity |
|---|---|
| Time | O(\log k) |
| Space | O(\log k) auxiliary |
Pattern: Bit Manipulation
Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 2802. Find The K-th Lucky Number is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Bit Manipulation.
The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2802. Find The K-th Lucky Number?
- LeetCode 2802. Find The K-th Lucky Number is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2802. Find The K-th Lucky Number?
- The Python solution on this page runs in O(\log k).
- What is the space complexity of LeetCode 2802. Find The K-th Lucky Number?
- The Python solution on this page uses O(\log k) auxiliary space.
- What topics does LeetCode 2802. Find The K-th Lucky Number cover?
- LeetCode 2802. Find The K-th Lucky Number is tagged Bit Manipulation, Math and String on LeetCode.
- Is LeetCode 2802. Find The K-th Lucky Number a premium problem?
- Yes. LeetCode 2802. Find The K-th Lucky Number is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.