python从1到n整数中1点的个数_从1到n整数中1出现的次数

输入一个整数n,求从1到n这n个整数的十进制表示中1出现的次数。例如输入12,从1到12这些整数中包含1的数字有1,10,11和12,1一共出现了5次

C++

class Solution {

public:

int NumberOf1Between1AndN_Solution(int n)

{

if(n<1)

return 0;

int count=0,round=n,base=1;

while(round)

{

int weight = round % 10;

round /= 10;

count += round *base;

if(weight==1)

count += (n % base) + 1;

else if(weight>1)

count += base;

base *=10;

}

return count;

}

};

python

# -*- coding:utf-8 -*-

class Solution:

def NumberOf1Between1AndN_Solution(self, n):

# write code here

if n < 1:

return 0

round,base,count = n,1,0

while round:

weight = round % 10

round /= 10

count += round * base

if weight == 1:

count += (n % base + 1)

elif weight > 1:

count += base

base *= 10

return count

后记总结的规律,以百位数为例:出现1 的个数 = (个位1出现次数)+(十位1出现次数)+(百位1出现次数)

534 = =(53*1+1)+(5*10+10)+(0*100+100)= 214

530 = (53*1)+(5*10+10)+(0*100+100) = 213

504 = (50*1+1)+(5*10)+(0*100+100) = 201

514 = (51*1+1)+(5*10+4+1)+(0*100+100) = 207

10 = (1*1)+(0*10+0+1) = 2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值