233 - Number of Digit One
2015-08-07 18:03
477 查看
Number of Digit One
Total Accepted: 307 TotalSubmissions: 1853
Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.
For example:
Given n = 13,
Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.
两经波折,一开始没想过会有大数的效率问题,后来发现,哦,原来考察的是找规律。
一开始的超时,最简单的解法:
int countDigitOne(int n) { int sum = 0; for(int i = 1; i <= n; i++) sum += count(i); return sum; } int count(int num) { int c = 0; while( num != 0 ) { if(num % 10 == 1) c++; num = num / 10; } return c; }
超时后,参照了其他人的解法,努力去理解公式:
ones += (a + 8) / 10 * m + (a % 10 == 1) * (b + 1);发现,我的思路不对,肯定不能遍历所有比 n 小的数字啊,这样太慢了,因为是有规律可循的。
但是理解上述公式还是很困难的,我现在能够理解了,是经过自己拿数字去对应公式,比如3456这个数,利用这个公式去推导每一位可能为1的所有比该数小的数字个数的总和。
慢慢的理解,就积累了一道这样找规律的题目。另外,注意 a 和 b 要为 long型(这是细节)。
int countDigitOne(int n) {
int ones = 0;
for(long m = 1; m <= n; m *= 10) {
long a = n / m;
long b = n % m;
ones += (a + 8) / 10 * m + (a % 10 == 1) * (b + 1);
}
return ones;
}
相关文章推荐
- 一张图记住Linux系统常用诊断工具
- 古代饮食
- 数组A包含0到n的所有整数,但其中缺了一个,且数组A里的整数都是用二进制形式存储,求这个缺失的整数
- 各国语言Unicode码网站
- centos 挂载移动硬盘
- iOS 常见 Crash 及解决方案
- Bootstrap的js插件之弹出框(popover)
- hdu 1045 && zoj 1002 Fire Net(DFS && 二分图匹配)
- wget下载整个网站---比较实用--比如抓取Smarty的document
- 选购兰花注意事项
- 蜂巢格网
- java编程思想随笔(1)
- 经典排序算法之堆排序
- 关于 ArtifactTransferException: Failure to transfer
- MySQL主从配置步骤
- bzoj 3211 分类: bzoj 2015...
- Webbench-http压力测试
- 使用ClickableSpan轻松实现一段文本中的多个点击事件
- poj 2406 Power Strings
- Arcgis for Java(一)在应用程序中添加地图