题目:输入一个整数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:"))))


Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐