Input: k =4Output: "47"Explanation: The first lucky number is4, the second one is7, the third one is44 and the fourth one is47.
Example 2:
1
2
3
4
Input: k =10Output: "477"Explanation: Here are lucky numbers sorted in increasing order:4,7,44,47,74,77,444,447,474,477. So the 10th lucky number is477.
Example 3:
1
2
3
Input: k =1000Output: "777747447"Explanation: It can be shown that the 1000th lucky number is777747447.
Every lucky number is made up of only ‘4’ and ‘7’. If we treat ‘4’ as 0 and ‘7’ as 1, the sequence of lucky numbers is just the sequence of binary numbers (starting from 1) mapped to ‘4’ and ‘7’. For example, the 4th lucky number is the binary 100, which is ‘47’.
classSolution {
public: string kthLuckyNumber(int k) {
string res;
string bin = bitset<32>(k).to_string();
auto it = bin.find('1');
for (int i = it +1; i < bin.size(); ++i) {
res += (bin[i] =='0'?'4':'7');
}
return res;
}
};