输入一个整数,求1~n这n个数的十进制表示1的个数。
将n的十进制的每一位单独拿出讨论,每一位的值记为weight。

1、个位
假若n=534。534的个位从0~9变化了53次,这53我们记为round。因为weight为4>0。因此第54轮为0~4,因此1出现了count=round+1。若weight为0,则出现count=round。
2、十位
与个位类似,但不同点在于从1~n,每增加10,十位的weight才加1。一轮周期0~9周期内所以1会出现10次。即count=round*10。当weight > 1时,在此场景下为3,因此第六轮出现了10次1。count = round*10 + 10。若weight为0,则count为round*10。
3、百位类似十位。
对其他位来说,记每一位的权值为base,位值为weight,该位之前的数是former。

则:
- 若weight为0,则1出现次数为round*base
- 若weight为1,则1出现次数为round*base+former+1
- 若weight大于1,则1出现次数为rount*base+base
比如:
534 = (个位1出现次数)+(十位1出现次数)+(百位1出现次数)=(53*1+1)+(5*10+10)+(0*100+100)= 214
function count(n) {
if (n < 1)
return 0;
var count = 0;
var round = n;
var base = 1;
while(round > 0) {
var 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;
}
console.log(count(534)); //214
本文介绍了一个算法,用于计算从1到任意整数n中数字1出现的总次数。通过分析n的每一位数字,算法巧妙地解决了这个问题,提供了一种高效的方法来统计1的个数。

被折叠的 条评论
为什么被折叠?



