挑7

題目描述

輸出7有關數字的個數,包括7的倍數,還有包含7的數字(如17,27,37...70,71,72,73...)的個數

輸入描述

一個正整數N。(N不大於30000)

輸出描述

不大於N的與7有關的數字個數,例如輸入20,與7有關的數字包括7,14,17.

輸入例子

20

輸出例子

3

算法實現

import java.util.Scanner;

/**
 * Declaration: All Rights Reserved !!!
 */
public class Main {
    public static void main(String[] args) {
//        Scanner scanner = new Scanner(System.in);
        Scanner scanner = new Scanner(Main.class.getClassLoader().getResourceAsStream("data.txt"));
        while (scanner.hasNext()) {
            int n = scanner.nextInt();
            System.out.println(countSeven(n));
        }

        scanner.close();
    }

    private static int countSeven(int n) {
        int result = 0;

        for (int i = 7; i <= n; i++) {
            if (i % 7 == 0) {
                result++;
            } else {
                // 某個數位上有1
                int m = i;
                while (m != 0) {
                    if (m % 10 == 7) {
                        result++;
                        break;
                    } else {
                        m /= 10;
                    }
                }
            }
        }

        return result;
    }
}
相關文章
相關標籤/搜索