1. 程式人生 > >統計從1到N中1的個數的演算法

統計從1到N中1的個數的演算法

問題:

給定一個十進位制正整數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