233. Number of Digit One
来源:互联网 发布:骂河南人被起诉 知乎 编辑:程序博客网 时间:2024/06/06 09:59
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.
//每10个数, 有一个个位是1, //每100个数, 有10个十位是1, //每1000个数, 有100个百位是1. //做一个循环, 每次计算 单个位上1 的总个数(个位,十位, 百位) //以算百位上1为例子: 假设百位上是0, 1, 和 >=2 三种情况: //case 1: n=3141092, a= 31410, b=92. 计算百位上1的个数应该为 3141 *100 次. //case 2: n=3141192, a= 31411, b=92. 计算百位上1的个数应该为 3141 *100 + (92+1) 次. //case 3: n=3141592, a= 31415, b=92. 计算百位上1的个数应该为 (3141+1) *100 次. //以上三种情况可以用 一个公式概括:m表示位数 //(a + 8) / 10 * m + (a % 10 == 1) * (b + 1);
class Solution {public: int countDigitOne(int n) { int ones = 0; for(long m = 1; m <= n; m *= 10) { long a = n / m; long b = n % m; ones += (a + 8) / 10 * m + (a % 10 == 1) * (b + 1); } return ones; }};
0 0
- 233. Number of Digit One
- 233. Number of Digit One
- 233. Number of Digit One
- 233. Number of Digit One
- 233. Number of Digit One
- 233. Number of Digit One
- 233. Number of Digit One
- Number of Digit One
- Number of Digit One
- Number of Digit One
- Number of Digit One
- Number of Digit One
- Number of Digit One
- Number of Digit One
- Number of Digit One
- Number of Digit One
- Number of Digit One
- Number of Digit One
- 《java入门第一季》之面向对象(匿名对象)
- php 函 数
- LeetCode 207. Course Schedule(课程安排)
- WebMvcConfigurationSupport
- 线程系列(三)--Liveness
- 233. Number of Digit One
- 为什么UDP有时比TCP更有优势?
- 112. Path Sum
- C++中注册表操作
- HDU 1010 DFS+剪枝
- eciplise android 出现导入不了layout文件的解决方法
- Emacs常用命令
- eclipse没有(添加)"Dynamic Web Project"选项的方法
- 2D array and dynamic array and dynamic 2D array