Skip to main content
Back to problems
#2802
Medium Algorithms

Find the k th lucky number

Math String Bit Manipulation
76.1% acceptance
Mar 31, 2026
64
15
We know that 4 and 7 are lucky digits. Also, a number is called lucky if it contains only lucky digits. You are given an integer k, return the kth lucky number represented as a string.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn kth_lucky_number(k: i32) -> String {
    let n = (k + 1) as u32;
    let bits = 32 - n.leading_zeros();
    let mut result = String::with_capacity(bits as usize - 1);
    for i in (0..bits - 1).rev() {
      if (n >> i) & 1 == 0 {
        result.push('4');
      } else {
        result.push('7');
      }
    }
    result
  }
}