当前位置:网站首页>剑指 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;
}
}
边栏推荐
- 陈强教授《机器学习及R应用》课程 第十四章作业
- kustomize entry example and basic syntax instructions
- 技术分享 | 接口自动化测试如何处理 Header cookie
- Redis源码剖析之数据过期(expire)
- 5G China unicom 直放站 网管协议 实时性要求
- FFmpeg多媒体文件处理(ffmpeg打印音视频Meta信息)
- Extract EventBus encapsulation to base class using annotations
- Flutter entry and advanced tour (6) Layout Widget
- Flutter入门进阶之旅(三)Text Widgets
- 电脑重装系统后桌面图标如何调小尺寸
猜你喜欢
Jenkins API groovy调用实践: Jenkins Core Api & Job DSL创建项目
Compensation transaction and idempotency guarantee based on CAP components
5G China unicom AP:B SMS ASCII Transcoding Requirements
注:检测到当前使用的ADB不是HBuilder内置或自定义ADB:PID为:9544进程名称为:adb.exe 路径为:c:\users\administrator\appdata\local\and
保存Simulink仿真模型为图片或者PDF的方法
Report: The number of students who want to learn AI has increased by 200%, and there are not enough teachers
How to reduce the size of desktop icons after the computer is reinstalled
kustomize入门示例及基本语法使用说明
Flutter Getting Started and Advanced Tour (8) Button Widget
Rust从入门到精通04-数据类型
随机推荐
AI basketball referee, walking is special, ask harden care don't care
ARM板卡增加路由功能
Introduction to Flutter advanced trip Dialog&Toast (10)
ERP不规范,同事两行泪 (转载非原创)
WSA toolkit installed app store tip doesn't work how to solve?
5G China unicom 一般性异常处理
About the handling of variable parameters in the Retrofit network request URL
Customize VIEW to realize in-app message reminder to rotate up and down
一维数组&指针
使用RecyclerView实现三级折叠列表
基于 R 语言的深度学习——简单回归案例
安踏携手华为运动健康共同验证冠军跑鞋 创新引领中国体育
造自己的芯,让谷歌买单!谷歌再度开源 180nm 工艺的芯片
JVM常用监控工具解释以及使用
Standing wave ratio calculation method
Flutter入门进阶之旅(十)Dialog&Toast
How to reduce the size of desktop icons after the computer is reinstalled
ftplib+ tqdm upload and download progress bar
关于Retrofit网络请求URL中含有可变参数的处理
handwritten big pile