Statementâ–¼
A number is called lucky if it comprises only the digits k
.Â
Constraints:
1<= k
<=109
Solution
The essence of this solution lies in using bitwise manipulation to generate the k-th lucky number. The solution uses an approach by transforming the given integer k
into a binary-like representation to determine the k-th lucky number. The key idea is to convert k
into a string of digits composed of
Now, let’s walk through the steps of the solution:
We start by adjusting
k
for 1-based indexing. Since lucky numbers are usually counted starting from the first (i.e., 1-based indexing), we incrementk
by1 . For example, ifk
=5 , it becomes6 after increment. This ensures the calculations align correctly with the expected sequence of lucky numbers.Next, we build the binary representation of incremented
k
, excluding the most significantÂ1 Â and any bits to the left of it. For example, if after incrementk
=6 , we convert it to‘0b110’ and to generate the lucky number, we exclude the most significant1 and the bits left to it. This leaves only the binary digits after the most significant1 that are‘10’ .Now, we replace binary digits with lucky digits in the resulting binary number. Every
‘0’ is replaced with‘4’ , and every‘1’ is replaced with‘7’ . This replacement transforms the binary-like sequence into the required lucky number format. For instance,‘10’ becomes‘74’ , aligning with the concept of lucky numbers composed of the digits4 and7 .Finally, the transformed string is returned as the k-th lucky number.
Let’s look at the following illustration to get a better understanding of the solution: