当前位置:网站首页>剑指 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;
}
}
边栏推荐
- Rust 入门指南(使用JSON)
- 绘制混合密度函数图以及添加分位数线
- ERP不规范,同事两行泪 (转载非原创)
- 我的2020年终总结
- read stream special attention
- ABP中的数据过滤器 (转载非原创)
- Flutter Getting Started and Advanced Tour (3) Text Widgets
- Report: The number of students who want to learn AI has increased by 200%, and there are not enough teachers
- Flutter Getting Started and Advanced Tour (4) Text Input Widget TextField
- 农村区县域农业电商如何做?数字化转型如何进行?
猜你喜欢

Say goodbye to the AI era of hand looms

Periodic sharing of Alibaba Da Tao system model governance

Rust从入门到精通04-数据类型
![[HCIP Continuous Update] Principle and Configuration of IS-IS Protocol](/img/4f/035432ac84644c4bd46573aa0ab7cd.png)
[HCIP Continuous Update] Principle and Configuration of IS-IS Protocol

WSA toolkit installed app store tip doesn't work how to solve?

AI basketball referee, walking is special, ask harden care don't care

史上最猛“员工”,疯狂吐槽亿万富翁老板小扎:那么有钱,还总穿着同样的衣服!...

ctfshow七夕杯2022

Flutter Getting Started and Advanced Tour (8) Button Widget

Flutter入门进阶之旅(四)文本输入Widget TextField
随机推荐
自定义VIEW实现应用内消息提醒上下轮播
AI basketball referee, walking is special, ask harden care don't care
SQL Server查询优化 (转载非原创)
ftplib+ tqdm upload and download progress bar
如何修改data work上jdbc驱动的版本
从NPU-SLAM-EDA技术分析
ansible-cmdb friendly display ansible collects host information
【HCIP持续更新】IS-IS协议原理与配置
Introduction to Flutter advanced trip Dialog&Toast (10)
Jenkins API groovy调用实践: Jenkins Core Api & Job DSL创建项目
5G China unicom general exception handling
用场景定义硬件,英码科技破解“边缘计算”密码
基于 R 语言的判别分析介绍与实践 LDA和QDA
uni-app - uview Swiper 轮播图组件点击跳转链接(点击后拿到 item 行数据, 取出数据做操作)
5G China unicom repeater network management protocol real-time requirements
数据挖掘-05
The new features of ABP 6.0.0 - rc. 1
保存Simulink仿真模型为图片或者PDF的方法
2022年非一线IT行业就业前景?
gin的中间件和路由分组