写一个函数,计算0到n之间2的个数 (1-9的个数)
2015-10-21 10:05
387 查看
题目
写一个函数,计算0到n之间2的个数。
解答
最简单直观的方法就是对于0到n之间的数,一个个地去统计2在它们上出现的个数, 然后累加起来即可。求2在某个数上出现的次数需要O(logn)的时间,一共有n个数, 所以共需要O(nlogn)的时间。代码如下:
1234567891011121314151617 | int Count2(int n){ int count = 0; while(n > 0){ if(n%10 == 2) ++count; n /= 10; } return count;} int Count2s1(int n){ int count = 0; for(int i=0; i<=n; ++i) count += Count2(i); return count; } |
1 2 | 当某一位的数字小于2时,那么该位出现2的次数为:更高位数字x当前位数 |
12 | 当某一位的数字等于2时,那么该位出现2的次数为:更高位数字x当前位数+低位数字+1 |
1 2 | 当某一位的数字大于2时,那么该位出现2的次数为:(更高位数字+1)x当前位数 |
12345678910111213141516171819202122232425262728 | int Count2s(int n){ int count = 0; int factor = 1; int low = 0, cur = 0, high = 0; while(n/factor != 0){ low = n - (n/factor) * factor;//低位数字 cur = (n/factor) % 10;//当前位数字 high = n / (factor*10);//高位数字 switch(cur){ case 0: case 1: count += high * factor; break; case 2: count += high * factor + low + 1; break; default: count += (high + 1) * factor; break; } factor *= 10; } return count;} |
1 2 3 4 | 当某一位的数字小于i时,那么该位出现i的次数为:更高位数字x当前位数 当某一位的数字等于i时,那么该位出现i的次数为:更高位数字x当前位数+低位数字+1 当某一位的数字大于i时,那么该位出现i的次数为:(更高位数字+1)x当前位数 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | int Countis(int n, int i){ if(i<1 || i>9) return -1;//i只能是1到9 int count = 0; int factor = 1; int low = 0, cur = 0, high = 0; while(n/factor != 0){ low = n - (n/factor) * factor;//低位数字 cur = (n/factor) % 10;//当前位数字 high = n / (factor*10);//高位数字 if(cur < i) count += high * factor; else if(cur == i) count += high * factor + low + 1; else count += (high + 1) * factor; factor *= 10; } return count; } |
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树
- [原创]java局域网聊天系统