题目链接: 剑指offer啊
题目描述: 输入N, 求从1到n整数中1出现的次数
解题思路: 一开始的想法只能是暴力, 但是自己太蠢了啊, 看了看剑指offer上的做法就是巧妙的利用了递归......一个数字可以拆成两部分: 拿21345举例来说, 可以拆成两部分:
1 ~ 1345, 01346 ~ 21345, 我们为什么要拆成这两个串呢, 因为第二部分我们可以准确的知道1 出现的次数, (拿第一位的值进行分类讨论), 第一部分我们可以递归, 这样我们就将问题划分成更小的子问题了, 所以问题可以求解, 注意边界情况子串长度为1 的时候, 和到字符串结尾 ' ' 的时候
代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <vector> #include <cmath> using namespace std; const int maxn = 1e2; int PowerBase10(int a, int n) { int res = 1; for( int i = 0; i < n; i++ ) { res *= 10; } return res; } int NumberOf1(const char *strN) { if( !strN || *strN < '0' || *strN > '9' || *strN == '