标签:col class style 出现 lse while bsp leetcode span
从低位到高位以此算出每个位含有一的个数。
以3104为例,将其分为三个部分:高位high、当前位cur、低位low
(1)算个位出现1的次数时:high = 310;cur = 4,low = 0.
0~309变化时cur只有为1一种情况,故有310个1,因为cur = 4,所以当高位为310时也有一个1;故个位出现1的次数count = 311;
(2)算十位时:high = 31,cur = 0, low = 4.
0~30每次变化时cur及low只有为10~19时有10个1,因为cur = 0,所以当高位为31时最大数字是3104,不会出现1,故十位出现1的次数count = 31 * 10 = 310;
(3)算百位时:high = 3, cur = 1; low = 4:
0~2每次变化时cur及low只有为100~199时有100个1,因为cur = 1, 所以当高位为3时,百位有5个1,即3100~3104,故百位出现1的次数count = 3 * 100 + 5 = 305;
(4)算千位时:high = 0, cur = 3, low = 104.
因为cur = 3,故cur及low为1000~1999时有1000个1,count = 1000.
加起来即可得count = 1926.
算法为:i = 1, 10,100...分别表示个位、十位、百位...
if(cur == 0)
count = high * i;
if (cur == 1)
count = high * i + low + 1;
if (cur > 1)
count = (high + 1) * i;
int countDigitOne(int n){ int i = 1; int count = 0; while ((n / i != 0) { int high; int cur; int low; high = n / (i * 10); cur = (n / i) % 10; low = n - (n / i * i); if (cur == 0) { count += (high * i); } else if (cur == 1) { count += (high * i) + low + 1; } else if (cur > 1) { count += (high + 1) * i; } i *= 10; } return count; }
2020/4/20
00:30
leetcode题:输入一个整数 n ,求1~n这n个整数的十进制表示中1出现的次数。
标签:col class style 出现 lse while bsp leetcode span
原文地址:https://www.cnblogs.com/zhengxunjie/p/12735299.html