一、问题描述
试计算在区间 1 到 n 的所有整数中,数字 x(0 ≤ x ≤ 9)共出现了多少次?例如,在 1 到 11 中,即在 1、2、3、4、5、6、7、8、9、10、11 中,数字 1 出现了 4 次。
二、思路
使用模运算,除10取余,计算出每一位数中 x 的个数,加起来
三、具体代码
import java.util.Scanner;public class Main { public static void main(String[] args) { // TODO Auto-generated method stub int result = 0; Scanner sc = new Scanner(System.in); int n = sc.nextInt(); //控制台输入 int x = sc.nextInt(); //控制台输入 for(int i =1;i<=n;i++){ int j = i; while(j>0){ if(j%10==x){ //个位数字等于x时, result + 1 result++; } j=j/10; } } System.out.println(result); sc.close(); }}