论文看不进去,到GeeksforGeeks思考个问题。。。
原题连接:http://www.geeksforgeeks.org/find-nth-number-number-system-3-4/
题目大意是,找出第N个十进制数,每一位要么是3要么是4,前几个符合条件的数为:3, 4, 33, 34, 43, 44, 333, 334, 343, 344, 433, 434, 443, 444, 3333, 3334, 3343, 3344, 3433, 3434, 3443, 3444, …
本来想的是不是按照因数只有2、3、5的第N个数,这种思路,但看了看,貌似不是,规律是k位数字都是3(k-1位数字),4(k-1为数字)
def GetNthNumberContainsOnly3And4(n):
"""
There 2 with 1 digit: 3, 4
There 4 with 2 digits: 33, 34, 43, 44
There 8 with 3 digits: 333, 334, 343, 344, 433, 434, 443, 444
...
We can conclude that(also by permutation analysis), there 2^k numbers with k digits
So the count of such numbers with no more than k digits is 2 + 4 + 8 + ... + 2^k = 2^(k+1) - 2
To get the nth number, we first figure out how many digits it has
>>> n <= 2^(k+1) - 2
>>> n+2 <= 2^(k+1)
>>> k = log2(n+2) - 1
Then we try to figure out whether it starts with 3 or not:
(1) we know there are 2^k-2 digits with no more than k-1 digits
(2) then the number is the (m = n-(2^k-2))th number with k digits
(3) consider the k-1 digits behind, we know there are 2^(k-1) such numbers with k-1 digits,
so if m <= 2^(k-1), then it starts with 3
otherwise it starts with 4 and the following part is the (m-2^(k-1))th number with k-1 digits
by apply the same methods we can get the 2th, 3th, ... kth digit of this number
"""
# figure how many digits
k = 1
while (1<<(k+1))-2 < n:
k += 1
# figure its order in those with k digits
n -= (1<<k) - 2
num = ''
for i in range(k):
cnt = 1 << (k-1-i)
if cnt >= n:
num += '3'
else:
num += '4'
n -= cnt
return int(num)
# test case
if __name__ == '__main__':
n = 30
for i in range(1, n + 1):
print(GetNthNumberContainsOnly3And4(i))