在从1到n的正数中1出现的次数

题目:输入一个整数n,求从1到n这n个整数的十进制表示中1出现的次数。

例如输入12,从1到12这些整数中包含1 的数字有1,10,11和12,1一共出现了5次。


呵呵,通过自己的分析搞定掉啦! 粘上代码~~~~~~~~~~~~~~


#!/bin/python
# coding: UTF-8
# copyleft: ICANTH, i can do anything what i can think 
# author 	: wenhui, 2012-6-19 9:03:03
# dscrp		: 输入一个整数n,求从1到n这n个整数的十进制表示中1出现的次数。
# 				if num(n) = 0	then f(n) 	= f(n-1) 
#					if num(n) = 1 then 
#									f(n-1) + num(n) * one_in_9len(n - 1) + num(1, n -1) + 1
#					if num(n) > 1 then
#									f(n-1) + num(n) * one_in_9len(n - 1) + 10^(n-1)

def one_in_9len( n ) :
	'''caclumate the 1's num between 1 and 99...9'''	
	return (n * 10 ** (n-1))
# one_in_9len

def convert_num(j, i) :
	return 1
	
def _count_1_in_N (num_str, n) :
	'''count the numbers of 1 in 1 ~ num_str[1...N].'''	
	
	def num_after_first() :
		if n <= 0 : 	return 0
		else : 				return int(num_str[n  - 1 - len(num_str): ])
	# num_exp_highest	
	
	def get_highest_digit() :
		return int(num_str[len(num_str) - n])
	# get_highest_digit
	
	if 	n == 0 :	return 0
	if 	n == 1 and num_str[-1] == '0':	return 0
	if 	n == 1 and num_str[-1] > '0':	return 1	
	
	highest_digit = get_highest_digit()
	total_ones = _count_1_in_N(num_str, n - 1)
	
	# if num(n) = 0	
	if highest_digit == 0 :	return total_ones
	total_ones += highest_digit * one_in_9len(n - 1)
	
	# if num(n) = 1
	if highest_digit == 1 :
		total_ones += 1 + num_after_first()
	# else if num(n) > 1
	else :
		total_ones += 2 **(n - 1)
	
	return total_ones	 
# end of _count_1_in_N

def count_1_in_N ( N ) :
	if N == 0 :	return 0
	if N < 9 : 	return 1

	num_str = str ( N )
	return _count_1_in_N(num_str, len(num_str))
# end of count_1_in_N

print( "\nthe count of number 1 is:\t", \
	count_1_in_N (int(input("Please input the number N:"))))


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值