题目:
输入一个整数 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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
代码:
class Solution {
public:
int countDigitOne(int n) {
if(n==0)return 0;
int length=floor(log10(n))+1;
if(length==1&&n>=1)return 1;
int boundary=n%int(pow(10,length-1));
int first=n/pow(10,length-1);
int firstpart=0,secondpart=0,thirdpart=0;
if(first==1){
firstpart=boundary+1;
}
else{
firstpart=pow(10,length-1);
}
secondpart=first*(length-1)*pow(10,length-2);
thirdpart=countDigitOne(boundary);
return firstpart+secondpart+thirdpart;
}
};
思路:以数字21345为例,将1的个数分为两部分,一部分是万位的1的个数,如果first数字大于1,那么firstpart=pow(10,length-1);如果first的数字等于1,那么firstpart=1345+1;第二部分是万位以后的1的个数,把21345分成1~1345和1346~21345两部分,第一部分采用递归计算,第二部分等于first*(length-1)*pow(10,length-2);主要思想就是分解加递归。