Skip to content

2802. Find The K-th Lucky Number 👍

  • Time: $O(\log k)$
  • Space: $O(\log k)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
 public:
  string kthLuckyNumber(int k) {
    string ans;

    for (int i = k + 1; i > 0; i /= 2)
      ans += i & 1 ? '7' : '4';

    reverse(ans.begin(), ans.end());
    return ans.substr(1);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
  public String kthLuckyNumber(int k) {
    StringBuilder sb = new StringBuilder();

    for (int i = k + 1; i > 0; i /= 2)
      sb.append((i & 1) == 1 ? '7' : '4');

    return sb.reverse().substring(1);
  }
}
1
2
3
class Solution:
  def kthLuckyNumber(self, k: int) -> str:
    return bin(k + 1)[3:].replace('0', '4').replace('1', '7')