Leetcode: Number of Digit One
来源:互联网 发布:旅游网站毕业设计源码 编辑:程序博客网 时间:2024/06/05 18:18
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; }};
0 0
- Number of Digit One 【leetcode】
- [leetcode] Number of Digit One
- [LeetCode] Number of Digit One
- LeetCode ||Number of Digit One
- Number of Digit One -- leetcode
- *LeetCode-Number of Digit One
- [LeetCode] Number of Digit One
- Leetcode Number of Digit One
- Leetcode: Number of Digit One
- Leetcode Number of Digit One
- leetcode:Number of Digit One
- 《leetCode》: Number of Digit One
- Leetcode Number of Digit One
- Number of Digit One leetcode
- leetcode 233: Number of Digit One
- Leetcode 233 Number of Digit One
- [leetcode] 233.Number of Digit One
- LeetCode-Number of Digit One-解题报告
- UVA11624 Fire!
- 程序运行时间计算
- 08-cmd定时关机和取消定时关机
- ubantu 安装tomcat
- iOS 学习笔记4-NSDictionary 和 NSMutableDictionary
- Leetcode: Number of Digit One
- POJ 3984 迷宫问题(bfs+打印路径)
- python的开发环境搭建
- Linux格式化硬盘 常用命令小记
- hdu1241 Oil Deposits
- 005-LAMP_MySQL binary installation
- 自学QT之图片操作(缩放、平移、扭曲和旋转等)
- 一次完整的HTTP请求所经历的7个步骤
- java异常学习笔记