LeetCode-Number of Digit One-解题报告
2015-07-09 14:04
393 查看
原题链接 https://leetcode.com/problems/number-of-digit-one/
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~n所有数中1出现的个数。
最一般的方法当然是一个一个数的去数。
还有一种方法就是数每一个数位上1出现的个数。
对于一个数 abcd
当 d > 1的时候 个位上出现1的个数为 (abc + 1)*1
当d = 1 的时候 个位上出现1的个数为 abc * 1 + 0 + 1, 0表示 d后面的数。对于11 来说,个位上出现1的数为 11,1
当d = 0的时候 个位上出现1的个数为 abc * 1
对于其它数位,相对的1变为10,100,1000..
class Solution {
public:
int countDigitOne(int n) {
long long ans = 0, base = 1, last = 0;
while (n)
{
int t = n % 10;
n /= 10;
if (t > 1)ans += (n + 1) * base;
else if (t == 1)ans += n*base + last + 1;
else ans += n*base;
last = t*base + last;
base *= 10;
}
return ans;
}
};
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~n所有数中1出现的个数。
最一般的方法当然是一个一个数的去数。
还有一种方法就是数每一个数位上1出现的个数。
对于一个数 abcd
当 d > 1的时候 个位上出现1的个数为 (abc + 1)*1
当d = 1 的时候 个位上出现1的个数为 abc * 1 + 0 + 1, 0表示 d后面的数。对于11 来说,个位上出现1的数为 11,1
当d = 0的时候 个位上出现1的个数为 abc * 1
对于其它数位,相对的1变为10,100,1000..
class Solution {
public:
int countDigitOne(int n) {
long long ans = 0, base = 1, last = 0;
while (n)
{
int t = n % 10;
n /= 10;
if (t > 1)ans += (n + 1) * base;
else if (t == 1)ans += n*base + last + 1;
else ans += n*base;
last = t*base + last;
base *= 10;
}
return ans;
}
};
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- C++ Custom Control控件向父窗体发送对应的消息
- C++中拷贝构造函数的应用详解