问题描述
输入一个整数 n ,求1~n这n个整数的十进制表示中1出现的次数。
例如,输入12,1~12这些整数中包含1 的数字有1、10、11和12,1一共出现了5次。
示例 1:
输入:n = 12
输出:5
示例 2:
输入:n = 13
输出:6
问题解决
暴力法
class Solution {
public int countDigitOne(int n) {
//暴力法解决
int res = 0;
for(int i = 1; i <= n; i++) {
res += getOneNumber(i);
}
return res;
}
public int getOneNumber(int i) {
int num = 0;
while(i > 0) {
if(i % 10 == 1) num++;
i /= 10;
}
return num;
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/1nzheng-shu-zhong-1chu-xian-de-ci-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。