[LeetCode] Number of Digit One
来源:互联网 发布:数据分析方法论 编辑:程序博客网 时间:2024/06/08 01:50
题意:计算从 1~n 中所有的数的 1 的个数总和。
题目链接:Number of Digit One
思路:代码来自《编程之美》2.4
1位数:
n >= 1, f(n) = 1,
n = 0, f(n) = 0
2位数:f(n) = 个位数1的个数 + 十位数1出现的个数;
个位数1的个数:个位数值>=1,1的个数为十位数数值加1;个位数为0,1的个数则为十位数数值;
十位数1的个数:十位数值=1,1的个数为个位数数值加1;十位数>1,1的个数为10;
3位数:f(n) = 个位数1的个数 + 十位数1出现的个数 + 百位数1出现的个数;
4位数:
5位数:
。
。
。
以此类推
代码如下:
/** * 1、找规律;2、注意越界。 */ public class Solution { public int countDigitOne(int n) { if(n <= 0) { return 0 ; } long iCount = 0 ; long iFactor = 1 ; long iLowerNum = 0 ; long iCurrNum = 0 ; long iHigherNum = 0 ; while(n / iFactor != 0) { iLowerNum = n - (n / iFactor) * iFactor ; iCurrNum = (n / iFactor) % 10 ; iHigherNum = n / (iFactor * 10) ; System.out.println(iHigherNum + ", " + iCurrNum + ", " + iLowerNum); switch((int) iCurrNum) { case 0: iCount += iHigherNum * iFactor ; break ; case 1: iCount += iHigherNum * iFactor + iLowerNum + 1 ; break ; default: iCount += (iHigherNum + 1) * iFactor ; break ; } iFactor *= 10 ; } return (int) iCount ; }}
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-解题报告
- SDN技术
- 尺度空间
- GB de 两年
- HDU 1172 猜数字
- 一个Linux下C线程池的实现
- [LeetCode] Number of Digit One
- debian 各种乱七八糟指令
- fread与fwrite
- bzoj-1467 clever Y / JDFZ-2940 EXBSGS
- UVa 10693 - Traffic Volume
- LIBSVM在python中的使用方法
- 重载与覆盖
- 管理系统权限模块技术方案
- 线程3:时间同步