第N个只包含3和4的数

论文看不进去,到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))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值