统计从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

原创粉丝点击