当前位置:网站首页>剑指 Offer 43. 1~n 整数中 1 出现的次数(递归、数学)
剑指 Offer 43. 1~n 整数中 1 出现的次数(递归、数学)
2022-08-09 12:45:00 【养猪去】
举个例子: n = 2304 。答案为四个部分之和:
- 所有小于等于2304的正整数中,个位出现1的次数.
- 所有小于等于2304的正整数中,十位出现1的次数.
- 所有小于等于2304的正整数中,百位出现1的次数.
- 所有小于等于2304的正整数中,千位出现1的次数.
循环地计算每个位上出现的1的次数。(个位、十位、百位、…)
class Solution {
public int countDigitOne(int n) {
// mulk 表示 10^k
// 在下面的代码中,可以发现 k 并没有被直接使用到(都是使用 10^k)
// 但为了让代码看起来更加直观,这里保留了 k
long mulk = 1;
int ans = 0;
// 1234 567
for (int k = 0; n >= mulk; ++k) {
ans += (n / (mulk * 10)) * mulk + Math.min(Math.max(n % (mulk * 10) - mulk + 1, 0), mulk);
mulk *= 10;
}
return ans;
}
}
边栏推荐
猜你喜欢

数据挖掘-05

Flutter Getting Started and Advanced Tour (4) Text Input Widget TextField

安踏携手华为运动健康共同验证冠军跑鞋 创新引领中国体育

ansible-cmdb friendly display ansible collects host information

5G Unicom Network Management Design Ideas

Flutter Getting Started and Advanced Tour (3) Text Widgets
![[HCIP Continuous Update] Principle and Configuration of IS-IS Protocol](/img/4f/035432ac84644c4bd46573aa0ab7cd.png)
[HCIP Continuous Update] Principle and Configuration of IS-IS Protocol

5G China unicom 直放站 网管协议 实时性要求

联通网管协议框图

Go Affair, How to Become a Gopher and Find a Go Job in 7 Days, Part 1
随机推荐
30行代码实现蚂蚁森林自动偷能量
Flutter Getting Started and Advanced Tour (3) Text Widgets
5G China unicom repeater network management protocol real-time requirements
Intra-group reverse order adjustment of K nodes
使用RecyclerView实现三级折叠列表
5G 联通网管设计思路
Ten minutes to teach you how to use VitePress to build and deploy a personal blog site
R 语言 2010.1至2021.12艾滋病每月发病人数 时间序列分析
Flutter Getting Started and Advanced Tour (7) GestureDetector
Periodic sharing of Alibaba Da Tao system model governance
Data Mining-06
数据挖掘-06
leetcode 20. Valid Parentheses 有效的括号(中等)
Bitmaps and bit operations
Rust 入门指南(使用JSON)
卷积神经网络表征可视化研究综述(1)
激光熔覆在农机修复强化中的应用及研究方向
How to save Simulink simulation model as image or PDF
Data Mining-05
Jenkins API groovy调用实践: Jenkins Core Api & Job DSL创建项目