输入一个整数 n ,求1~n这n个整数的十进制表示中1出现的次数。
例如,输入12,1~12这些整数中包含1 的数字有1、10、11和12,1一共出现了5次。
示例 1:
输入:n = 12 输出:5 示例 2:
输入:n = 13 输出:6
限制:
1 <= n < 2^31
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/1nzheng-shu-zhong-1chu-xian-de-ci-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
利用密码锁思想,固定一位变化其他位 就能组成不同的组合。考虑每位0到9的情况,有多少个1.
假如当前位是0,那么高位*当前位的位数,
如果当前位是1 那么还需要考虑低位有多少种可能
如果当前位是234…等 那么高位+1再 * 当前位
class Solution {
public:
int countDigitOne(int n) {
int high=n/10;//高位
int cur=n%10;//当前位数字
int low=0;//低位
long digit=1;//当前位数
int res=0;
while(high!=0||cur!=0)//当高位和当前位都为0时 遍历完成
{
if(cur==0)res+=digit*high;
else if(cur==1)res+=(digit*high)+low+1;
else res+=(high+1)*digit;
low+=cur*digit;
cur=high%10;
high/=10;
digit*=10;
}
return res;
}
};