[leetcode-233]Number of Digit One(C)
2015-08-24 16:41
197 查看
问题描述:
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时,有多少种情况,然后将这些情况累加。
注意对于某一位进行考虑时,自然的将整个数分为高位和低位两部分。而对某一位而言:它只会出现三种情况,0,1或者大于1.
0:当为0的时候,肯定会向上借位。(首位不可能为0,所以肯定会有位可借)。那此时低位可以取任意值。即:(high)*10^(低位位数)
1:当为1的时候,把高位和低位拼接起来,那最多存在这么多+1个的可能。即high*base+low;
>1:当>1时,那么就会有(high+1)*10^(低位位数)
代码如下:0ms
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时,有多少种情况,然后将这些情况累加。
注意对于某一位进行考虑时,自然的将整个数分为高位和低位两部分。而对某一位而言:它只会出现三种情况,0,1或者大于1.
0:当为0的时候,肯定会向上借位。(首位不可能为0,所以肯定会有位可借)。那此时低位可以取任意值。即:(high)*10^(低位位数)
1:当为1的时候,把高位和低位拼接起来,那最多存在这么多+1个的可能。即high*base+low;
>1:当>1时,那么就会有(high+1)*10^(低位位数)
代码如下:0ms
[code]int countDigitOne(int n) { int base = 1; int count = 0; int low = 0;//低位部分 if(n<0) return 0; while(n!=0){ int val = n%10; int high = n/10; switch (val){ case 0: count+=high*base; break; case 1: count+=high*base+low+1; break; default: count+=(high+1)*base; } low += val*base; base*=10; n = n/10; } return count; }
相关文章推荐
- android中volley框架源码解析
- Linux中exec命令
- 辞职了公积金怎么办
- 【LeetCode】(9)Palindrome Number(Easy)
- javascript通过数日两个日期之间的比较分离
- 数据库存取图片
- activemq 在tomcat上部署
- MySQL/MariaDB数据库主从复制
- HDC、CDC、CWindowDC、CClientDC……
- git commit的一些操作
- 名词解释RPO和RTO
- 黑马程序员_面向对象之构造方法
- android- monkey命令详解
- network namespace 与veth pair
- 继承和组合
- springMVC中文乱码
- UNIX SIGIO信号的使用http://blog.csdn.net/msda/article/details/8090748
- C++初始化函数列表
- c++ 泛型编程
- redis配置文件说明--redis.conf