【华为机试055】挑7

题目描述:

输出7有关数字的个数,包括7的倍数,还有包含7的数字(如17,27,37...70,71,72,73...)的个数 

Java实现:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            int n = sc.nextInt();
            int count = 0;
            for (int i = 1; i <= n; i++) {
                if (beishu(i) || baohan(i))
                    count++;
            }
            System.out.println(count);
        }
    }

    private static boolean beishu(int n) {
        if (n % 7 == 0)
            return true;
        return false;
    }

    private static boolean baohan(int n) {
        String strn = String.valueOf(n);
        if (strn.contains("7"))
            return true;
        return false;
    }
}

关键点:

  • 因为n的范围较小并且只需要得到个数,因此用遍历的方法

猜你喜欢

转载自blog.csdn.net/heyiamcoming/article/details/81066273