统计从1到N中1的个数的算法
来源:互联网 发布:三维数组 python 编辑:程序博客网 时间:2024/06/07 03:47
问题:
给定一个十进制正整数N,写下从1开始,到N的所有整数,然后数一下其中出现的所有“1”的个数。例如:
N= 2,写下1,2。这样,1的个数是1。N= 12,我们会写下1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12。这样,1的个数是5。
算法a如下:
public static int getOneCount(int n){ int count = 0; if(n < 1){ return 0; }else { for (int i = 1; i <= n; i++){ int j = i; while (j > 0){ if (j % 10 == 1){ count++; } j = j/10; } } } return count; }其他方法b:
public static int getOneCount2(int n){ int count = 0; if(n < 1){ return 0; }else { for (int i = 1; i <= n; i++){ String s = String.valueOf(i); if (!s.contains("1")){ continue; }else { char[] cs = s.toCharArray(); for (char c : cs){ if (c=='1') { count++; } } } } } return count; }其他方法c:
public static int getOneCount3(int n){ int count = 0; if(n < 1){ return 0; }else { for (int i = 1; i <= n; i++){ String s = String.valueOf(i); count = count + appearNumber(s, "1"); } } return count; } public static int appearNumber(String srcText, String findText) { int count = 0; Pattern p = Pattern.compile(findText); Matcher m = p.matcher(srcText); while (m.find()) { count++; } return count; }
PS:以上都是面试过程中想到的.
效率getOneCount > getOneCount2 > getOneCount3
算法a适合1到9,后面两个实现方法可以适合0到9
阅读全文
1 0
- 统计从1到n中1的个数
- 统计从1到N中1的个数的算法
- 统计从1到N的所有整数中出现1的个数
- 从1到N中,统计所有含有1的个数。
- 统计1到n中1的出现个数
- 统计0到n中1的个数
- 统计1到n这n个数中出现1的个数
- 从1到n的数字中1的个数
- 从1到n整数中1出现的个数
- 算法--求0到N中所有1的个数
- 统计1到N中1的个数,并找出满足飞fun(n)=n的最大n值
- 给定一个正整数N,统计从1到N的整数中,出现“1”的个数(11这个数算出现两次)
- 统计0到n之间1的个数
- 统计0到n之间1的个数[数学]
- 统计0到n之间1的个数
- 统计0到n之间1的个数
- 统计0到n之间1的个数
- 统计1到n之间的所有数字中1出现的个数
- 编写servalet时引入第三方类抛出classnotfoundexception异常解决方法
- Linux_Arithmetic_Sequence
- C++ vector类模板和auto关键字
- Android AIDL简单分析
- Linux下Redis的安装和部署
- 统计从1到N中1的个数的算法
- centos6安装ftp服务
- 键盘录入数据模拟单项选择题
- Shell参数(Shell Parameters)
- 数据结构实验之栈与队列七:出栈序列判定
- Python 学习笔记 -了解
- 最长公共子序列(简化代码)
- CodeForces 279B
- UWP初学的磕磕绊绊:Release版本下GetProperties()方法不能用?