输出7有关数字的个数,包括7的倍数,还有包含7的数字(如17,27,37...70,71,72,73...)的个数(一组测试用例里可能有多组数据,请注意处理)
例:输入20,输出3(7,14,17)
思路:从7开始遍历数字,当这个数对7取余为0或此数包含7字符,则加入结果集
时间复杂度为O(n)
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNext()){ select7(scanner.nextInt()); } } private static void select7(int n) { StringBuilder result = new StringBuilder(); int count = 0; for (int i = 7; i <= n; i++) { if(i % 7 == 0){ result.append(i).append(","); count++; } else { String str = i + ""; if(str.contains("7")){ result.append(i).append(","); count++; } } } System.out.println(count); }