一道据说是Google的面试题

一道据说是Google的面试题
题目:有一个整数n,写一个函数f(n),返回0到n之间出现的"1"的个数。比如f(13)=6 ; f(11)=4,算出f(n)=n的n(如f(1)=1)?
我用python写了一份代码,还改写了一份c++代码

python源代码
def count(i):
"""count form 0 to this number contain how many 1
1.you shoul know pow(10,n)-1 contain 1 number is n*pow(10,n-1)
2.use 32123 for example:
from 10000 to 32123 the first digit contain 1 number is 1(0000-9999) = pow(10,4) ,
and from 10000 to 30000 the rest digit contain 1 number is ( firstDigit*4*pow(10,4-1) )
so count(32123)=pow(10,4)+( firstDigit*4*pow(10,4-1) ) + count(2123)

print count(1599985)
1599985

print count(8)
1
"""
if i==0:
return 0
if 9>=i>=1:
return 1
digit=len(str(i))
firstDigit=int(str(i)[0])
if firstDigit>1:
now=pow(10,digit-1)
else:
now=int(str(i)[1:])+1
now+=(digit-1)*pow(10,digit-2) * firstDigit
return now+count(int(str(i)[1:]))

def little(i):
count_i=count(i)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值