[Leetcode 233, Medium] Number of Digit One
2015-08-03 03:49
375 查看
Problem:
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.
Hint:
Beware of overflow.
Analysis:
Solutions:
C++:
Python:
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.
Hint:
Beware of overflow.
Analysis:
Solutions:
C++:
int countDigitOne(int n) { int num = 0; if(n <= 0) return num; long long base = 10; if(n < base) return 1; for(; 10 * base <= n; base *= 10); if(n == base) { num = base / 10 + 10 * countDigitOne(base / 10- 1) + 1; } else if(n % base == 0) { num = base + (n / base) * countDigitOne(base - 1); } else if(n / base > 1) { num = base + (n / base) * countDigitOne(base - 1) + countDigitOne(n % base); } else { num = n % base + 1 + countDigitOne(base - 1) + countDigitOne(n % base); } return num; }Java:
Python:
相关文章推荐
- [Leetcode 242, Easy] Valid Anagram
- [LeetCode] Best Time to Buy and Sell Stock III
- JavaAnnotation
- C#中WebClient使用DownloadString中文乱码的解决办法
- JavaJMS
- LeetCode Count Primes
- LeetCode Count Primes
- IO
- JavaMail
- PHP之GD库
- 将dll放进exe[.Net]
- Java Annotation
- c#的DateTime.Now函数详解
- Java_Collection
- XSS 平台搭建与优化(基于 xsser.me 源码)
- 用Mediawiki做百科网站资源大参考
- 用Mediawiki做百科网站资源大参考
- Leetcode #88 Merge Sorted Array
- ubutun 下webalizer 分析Apache日志
- 网站流量统计系统 phpMyVisites