Leetcode: Number of Digit One
2016-01-17 23:35
239 查看
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的次数为高位代表的数字乘以当前位的大小,然后考虑一下边界条件,当前位小于或者正好等于1的情况。
class Solution {
public:
int countDigitOne(int n) {
if (n <= 0) {
return 0;
}
int counts = 0;
int lowUnit = 1;
int lowNum = 0;
while (n > 0) {
int highNum = n / 10;
counts += highNum * lowUnit;
if (n % 10 > 1) {
counts += lowUnit;
}
else if (n % 10 == 1) {
counts += lowNum + 1;
}
lowNum += (n % 10) * lowUnit;
n /= 10;
lowUnit *= 10;
}
return counts;
}
};
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的次数为高位代表的数字乘以当前位的大小,然后考虑一下边界条件,当前位小于或者正好等于1的情况。
class Solution {
public:
int countDigitOne(int n) {
if (n <= 0) {
return 0;
}
int counts = 0;
int lowUnit = 1;
int lowNum = 0;
while (n > 0) {
int highNum = n / 10;
counts += highNum * lowUnit;
if (n % 10 > 1) {
counts += lowUnit;
}
else if (n % 10 == 1) {
counts += lowNum + 1;
}
lowNum += (n % 10) * lowUnit;
n /= 10;
lowUnit *= 10;
}
return counts;
}
};
相关文章推荐
- 用批处理解决数学问题的代码第1/4页
- php常用数学函数汇总
- 无限循环小数
- 数学书籍备忘
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- 建立以人为本的数学课程观
- 文兴小学2008-2009学年度第一学期数学科教学计划
- MySql函数大全<二>
- 一生受用的数学公式
- oracle中行列转换
- 数学猜想
- 世界第一数学强校的背后
- 数学是一种思考方式
- 【巧用数学面板达成书写表达式】
- C语言产生随机数
- shell浮点运算工具bc
- 论数学