洛谷OJP1980計數問題試計算在區間 1 到 n 的所有整數中,數字 x(0 ≤ x ≤ 9) 共出現了多少次?
阿新 • • 發佈:2019-01-23
題目描述
試計算在區間 1 到 n 的所有整數中,數字 x(0 ≤ x ≤ 9) 共出現了多少次?例如,在 1 到 11 中,即在 1,2,3,4,5,6,7,8,9,10,11中,數字 1 出現了 4 次。
輸入輸出格式
輸入格式:
2 個整數 n,x ,之間用一個空格隔開。
輸出格式:
1 個整數,表示 x 出現的次數。
輸入輸出樣例
輸入樣例#1:
11 1
輸出樣例#1:
4
說明
對於 100\%100% 的資料, 1≤ n ≤ 1,000,000,0 ≤ x ≤ 91≤n≤1,000,000,0≤x≤9 。
AC程式碼(兩種方法)
第一種(JAVA實現)
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
int n=in.nextInt();
int x=in.nextInt();
String strx=String.valueOf(x);
char cx=strx.charAt(0);//將整數變換成字元
int total=0;
for(int i=1;i<=n;i++)
{
String str=String.valueOf(i);//將整數變換為字串
for(int j=0;j<str.length();j++)
{
if(str.charAt(j)==cx) total++; //遍歷字串中的每一個字元
}
}
System.out.println(total);
}
}
第二種方法(C++實現)
#include<iostream>
using namespace std;
int main()
{
long long n,i,x,b,c,t=0;
cin >>n>>x;//輸入範圍與要查的數字;
for(i=1;i<=n;i++)//一到n進行迴圈;
{
b=i;//為了不改變i的值,就把i賦值給一個數;
while(b!=0)//如果b不等於0,繼續迴圈;
{
c=b%10;//求是否是x,是的話計數器加一;
b=b/10;//求下一個數字是否為x;
if(c==x) t++;計數器加一;
}
}
cout<<t<<endl;//輸出計數器的數字;
return 0;//結束
}