[LeetCode] Find The K-th Lucky Number

2802. Find The K-th Lucky Number

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
string kthLuckyNumber(int k) {
k -= 1;
int n = 1, po = 2, x = 0;
while(x + po <= k) {
x += po;
n += 1;
po *= 2;
}
k -= x;
string res(n,'4');
for(int i = n - 1, j = 0; i >= 0; i--,j++) {
if((k >> j) & 1) res[i] = '7';
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/09/09/PS/LeetCode/find-the-k-th-lucky-number/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.