[LeetCode] Number of Digit One
2015-07-08 01:50
197 查看
The following idea is taken from a book named 《剑指offer》 published in China.
Suppose
The code is as follows.
This link has a brilliant 4-line solution! The code is rewritten as follows.
Suppose
n = 271, it then breaks
[1, 271]into
[1, 71]and
[72, 271]. For
[72, 271], the number of
1on the hundreds are
10^2 = 100(note that if the digit on the higest bit is
1, then the number of
1's on that bit will be
72, which is
271 % 100 + 1). To compute the number of
1on tens and units, we further break
[72, 271]into
[72, 171]and
[172, 271]. Each interval has
10^1 = 10
1's on both the tens and units. So the overall number of
1's on tens and units is
2 * 2 * 10^1 = 40. Now we are only left with
[1, 71], which can be solved recursively. The
int nis transformed into a
string numto facilitate some operations.
The code is as follows.
class Solution { public: int countDigitOne(int n) { if (n <= 0) return 0; string num = to_string(n); return countOne(num); } private: int countOne(string num) { if (num.empty()) return 0; int first = num[0] - '0'; if (num.length() == 1) { if (first) return 1; return 0; } int highestBit; if (first > 1) highestBit = powerTen(num.length() - 1); else if (first == 1) highestBit = stoi(num.substr(1)) + 1; int otherBits = first * (num.length() - 1) * powerTen(num.length() - 2); int recurCount = countOne(num.substr(1)); return highestBit + otherBits + recurCount; } int powerTen(int exp) { int p = 1; for (int i = 0; i < exp; i++) p *= 10; return p; } };
This link has a brilliant 4-line solution! The code is rewritten as follows.
class Solution { public: int countDigitOne(int n) { int counts = 0; for (int m = 1000000000; m; m /= 10) counts += (n / m + 8) / 10 * m + (n / m % 10 == 1) * (n % m + 1); return counts; } };
相关文章推荐
- 图形管线之旅 Part2
- 在ubuntu14.04上安装emacs24.4
- 3.工厂方法模式(Factory Method)
- 鼠标在某个控件上按下,然后离开后弹起,如何捕获这个鼠标弹起事件
- Unity ScriptingAPI Vector3学习
- fans-rt 任务调度-堆栈切换篇(1)任务切换的基本原理
- Java中的递归原理分析
- SystemTrayDemo
- IIS 10.0 无法安装 URL rewrite重写模块 2.0
- scrollview滚动到指定区域的两种方法
- IOS小技巧——使用FMDB时如何把一个对像中的NSArray数组属性存到表中
- Number of Digit One
- 设计一个算法,判断一个二叉树是否为完全二叉树
- Swift基本使用-函数和闭包(三)
- 使用Unity3D的设计思想实现一个简单的C#赛车游戏场景
- 黑马程序员----java中的IO流基础
- Swift基本使用-控制流(二)
- IOS小技巧——如何使用GCD创建单例模式
- ubuntu15.04安装vm11
- 2.简单工厂模式(Simple Factory)