剑指offer_整数中1出现的次数
来源:互联网 发布:枪口动能计算器软件 编辑:程序博客网 时间:2024/05/21 16:20
题目:
求1~n的数字中,数字1出现的次数。
最无脑的做法,从1遍历到n,累计每个数字中1出现的次数。。。。
在leetcode上看到最牛逼的做法
先上代码再说:
public int countDigitOne(int n) { int ones = 0; for (long m = 1; m <= n; m *= 10) ones += (n/m + 8) / 10 * m + (n/m % 10 == 1 ? n%m + 1 : 0); return ones;}
就是这么简洁!!!
时间复杂度达到了O(lgn)!!!
看一下leetcode上面大神的解释:
https://discuss.leetcode.com/topic/18054/4-lines-o-log-n-c-java-python
For each position, split the decimal representation into two parts, for example split n=3141592 into a=31415 and b=92 when we’re at m=100 for analyzing the hundreds-digit. And then we know that the hundreds-digit of n is 1 for prefixes “” to “3141”, i.e., 3142 times. Each of those times is a streak, though. Because it’s the hundreds-digit, each streak is 100 long. So (a / 10 + 1) * 100 times, the hundreds-digit is 1.
Consider the thousands-digit, i.e., when m=1000. Then a=3141 and b=592. The thousands-digit is 1 for prefixes “” to “314”, so 315 times. And each time is a streak of 1000 numbers. However, since the thousands-digit is a 1, the very last streak isn’t 1000 numbers but only 593 numbers, for the suffixes “000” to “592”. So (a / 10 * 1000) + (b + 1) times, the thousands-digit is 1.
The case distincton between the current digit/position being 0, 1 and >=2 can easily be done in one expression. With (a + 8) / 10 you get the number of full streaks, and a % 10 == 1 tells you whether to add a partial streak.
根本在于利用数学对数字的分析,直接推出了简洁的数学公式。
在苏宁的笔试中,遇到过这么一道题,n个人中有m对好友(两两称为一对),朋友的朋友都算是同一个朋友圈。问有多少个朋友圈。
咋一看,毫无头绪,其实也是道数学题。
当m>n
时,只有1个朋友圈;
当m<n
时,有n-m个朋友圈
就是这么简单。。。。。。。。。。。。。
- 剑指offer_整数中1出现的次数
- 剑指Offer_面试题32_从1到n整数中1出现的次数(预留未解决)
- 剑指offer_数组中出现次数超过一半的数字
- 剑指offer_数字在排序数组中出现的次数
- :整数中1出现的次数
- 整数中1出现的次数
- 整数中1出现的次数
- 整数中1出现的次数
- 整数中1出现的次数
- 整数中1出现的次数
- 整数中1出现的次数
- 整数中1出现的次数
- 整数中1出现的次数
- 整数中1出现的次数
- 整数中1出现的次数
- 整数中1出现的次数
- 整数中1出现的次数
- 整数中1出现的次数
- javax.servlet.jsp.JspException cannot be resolved to a type
- 优先读者的读者/写者问题的算法设计
- CancelIO的作用:防止为发送的数据丢失
- JZOJ 4810 【NOIP2016提高A组五校联考1】道路规划
- Java的反射基本概念、语法和应用
- 剑指offer_整数中1出现的次数
- Linux嵌入式开发常见面试题
- 同义词总结
- HDU 5918 Sequence I kmp算法+虽然暴力也能过
- 2016华为校招上机试题2——洞穴逃生
- 3. Longest Substring Without Repeating Characters
- 51.[Python]使用multiprocessing进行多进程编程
- 51nod 1007 正整数分组(01背包)
- Integer Replacement