Java-数字中至少有一个7和一个9的数字



我必须编码一个程序,以确定1,000,000以下的正整数至少有一个7,而在其数字中至少有一个9,通过检查每个数字从1到999,999的数字("蛮力"方法)。答案应该为199,262。请帮忙!

如果包含7 9

,将数字转换为字符串和文本怎么样
    int count = 0;
    for (int i = 1; i < 1000000; i++) {
        String text = String.valueOf(i);
        // contains both
        if (text.contains("7") && text.contains("9")) count++;
    }
    System.out.println(count);

适合您的一些组合学:

没有7(或没有9)的两个数字的数字:

8*(9^1) = 72

没有9或7的2位数字的数量:

7*(8^1) = 56

2位数字的数量:

9*(10^1) = 90

至少一个7和一个9:

的2位数字数量
90 - 2*72 + 56 = 2

n位计算的公式:

= 9*(10^(d-1)) - 2*8*(9^(d-1)) + 7*(8^(d-1))

  9*(10^1+10^2+10^3+10^4+10^5) 
- 2*8*(9^1+9^2+9^3+9^4+9^5)
+ 7*(8^1+8^2+8^3+8^4+8^5) 
= 199262

蛮力算法:

public int count() {
    int count = 0;
    boolean per7 = false;
    boolean per9 = false;
    for (int i = 0; i < 1000000; i++) {
        int j = i;
        while ((!(per7 && per9)) && j > 1) {
            if (j%10 == 7) {
                per7 = true;
            } if (j%10 == 9) {
                per9 = true;
            }
            j = j/10;
        }
        if (per7 && per9) {
            count++;
        }
        per7 = false;
        per9 = false;
    }
    return count;
}

另一方面,我建议使用有关Compinatorics的基本知识,但是我知道,在研究中,我们经常做愚蠢的任务来学习某些技能。

最新更新