leetcode 233. Number of Digit One 从1到n的数组中出现数字1的数量 + 寻找规律,公式计算
2017-09-25 14:29
771 查看
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.
这道题是查1的数量,网上看了个做法,但是没搞懂,后来我突发奇想到使用字符串来做,但是超时,但是先这么办吧。
代码如下:
下面是C++的做法,看了很久才明白这一道题的意思,我最直接的做法就是使用字符串做判断,但是肯定会超时,所以我参考了网上的一个做法,就是找规律做的
代码如下:
For example:
Given n = 13,
Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.
这道题是查1的数量,网上看了个做法,但是没搞懂,后来我突发奇想到使用字符串来做,但是超时,但是先这么办吧。
代码如下:
/* * http://www.cnblogs.com/grandyang/p/4629032.html * * 搞不懂 * */ public class Solution { public int countDigitOne(int n) { int res = 0, a = 1, b = 1; while (n > 0) { if((n % 10 == 1)) res += (n + 8) / 10 * a + b; else res += (n + 8) / 10 * a; b += n % 10 * a; a *= 10; n /= 10; } return res; } /* * 我通过字符串来做,但是超时 * */ public int countDigitOneByStr(int n) { int count=0; StringBuilder builder=new StringBuilder(); for(int i=1;i<=n;i++) builder.append(i+""); for(int i=0;i<builder.length();i++) { if(builder.charAt(i)=='1') count++; } return count; } }
下面是C++的做法,看了很久才明白这一道题的意思,我最直接的做法就是使用字符串做判断,但是肯定会超时,所以我参考了网上的一个做法,就是找规律做的
代码如下:
#include <iostream> #include <algorithm> #include <vector> #include <set> #include <string> #include <map> using namespace std; class Solution { public: int countDigitOne(int n) { int res = 0, a = 1, b = 1; while (n > 0) { if ((n % 10 == 1)) res += (n + 8) / 10 * a + b; else res += (n + 8) / 10 * a; b += n % 10 * a; a *= 10; n /= 10; } return res; } };
相关文章推荐
- [分析总结:leetcode-Number of Digit One]寻找整数1到n之间所有数字中1出现的次数
- [Leetcode,python] Find All Numbers Disappeared in an Array 寻找数组中消失的数字
- 算法Week02.04 - LeetCode 233. Number of Digit One
- leetcode No233. Number of Digit One
- 二分法计算有序数组中数字出现的次数
- Number of Digit One 计算十进制1出现的个数
- [Leetcode,python] Find All Numbers Disappeared in an Array 寻找数组中消失的数字
- leetcode 400. Nth Digit 从1到n第n位数字是什么 + 找规律
- 233. Number of Digit One *HARD* -- 从1到n的整数中数字1出现的次数
- 将数组A中的内容和数组B中的内容进行交换,计算1/1-1/2+1/3-1/4+1/5 …… + 1/99 - 1/100 的值,1到 100 的所有整数中出现多少次数字9。
- 计算数组中每个数字出现多少次--“Bucket”桶的思想
- [Leetcode,python] Find All Numbers Disappeared in an Array 寻找数组中消失的数字
- LeetCode 448. Find All Numbers Disappeared in an Array (在数组中找到没有出现的数字)
- 合法IP&窗口最大值数组&打印素数&递归逆序一个栈&栈排序另一个栈&MyString&寻找数组中出现的重复字符&数组中的重复数字&逆序打印链表&空格替换成%20
- [LeetCode]233. Number of Digit One
- 寻找发帖水王(找出数组出现超过一半的数字)
- LeetCode 260 Single Number III(数组中只出现一次的数字3)
- 【算法22】寻找数组中出现次数超过一半的数字
- [leetcode]233. Number of Digit One
- leetcode 222. Count Complete Tree Nodes 计算满二叉树的节点数量 + DFS深度优先遍历 + 公式计算