LeetCode "Number of Digit One"
2015-07-08 14:45
295 查看
Marked as mathematics problem, but if you are able to divide 1s into several cases, the AC code becomes natural.
Lesson learnt: visualization in mind is always helpful.
And this link is amazing: https://leetcode.com/discuss/44281/4-lines-o-log-n-c-java-python - Count it digit by digit.
class Solution { unordered_map<long long, int> memo; public: int countDigitOne(int n) { if (n < 10) return n < 1 ? 0 : 1; if (memo.find(n) != memo.end()) return memo ; int base = pow(10, floor(log10(n))); int v = n / base; int r = n % base; int cnt0 = countDigitOne(base - 1); int cnt1 = 0; if (v == 1) { cnt1 = r + 1; } else { cnt1 = base + cnt0; cnt1 += (v - 2) * cnt0; } int ret = cnt0 + cnt1 + countDigitOne(r); memo = ret; return ret; } };
Lesson learnt: visualization in mind is always helpful.
And this link is amazing: https://leetcode.com/discuss/44281/4-lines-o-log-n-c-java-python - Count it digit by digit.
相关文章推荐
- getchar()用法
- 1015. Reversible Primes (20)
- 织梦dedecms — 图片集内所有图片调用(原图)
- Flex中容易忽略的属性默认值
- linux上安装配置vsftpd
- VS中CUDA与C++工程项目的配置
- JVM监控工具介绍jstack, jconsole, jinfo, jmap, jdb, jstat
- https server
- 自定义圆形进度条
- C++高精度性能测试函数
- 《算法入门经典大赛——培训指南》第二章考试
- 黑马程序员——OC—OC中面向对象的特性之封装
- [leetcode] 230.Kth Smallest Element in a BST
- C函数的模拟重载实现说明
- PRML1-引言
- WiFi连上了,却上不了网,请看这里
- jfinal框架中ajax提交返回类型datatype不确定时。。。
- 自定义属性时TypedArray的使用方法
- C中的位域与大小端问题
- hdoj 1226 超级password 【隐图BFS】