1. 程式人生 > 其它 >Problem:數字統計

Problem:數字統計

技術標籤:演算法c++

Problem Description

請統計某個給定範圍[L, R]的所有整數中,數字 2 出現的次數。

比如給定範圍[2, 22],數字 2 在數 2 中出現了 1 次,在數 12 中出現 1 次,在數 20 中出現 1 次,在數 21 中出現 1 次,在數 22 中出現 2 次,所以數字 2 在該範圍內一共出現了 6 次。

Input Format

輸入共 1 行,為兩個正整數 L 和 R,之間用一個空格隔開。

Output Format

輸出共 1 行,表示數字 2 出現的次數。

Scope of Data

1 ≤ L ≤ R ≤ 10000

Sample Input

在這裡插入圖片描述

Sample Output

在這裡插入圖片描述

Idea

列舉法

Program Code

#include <iostream>

using namespace std;

int l, r;

int main()
{
    int cnt = 0;

    cin >> l >> r;

    for(int i = l; i <= r; ++ i)
    {
        int t = i;
        while(t)
        {
            if(t % 10 == 2)
            {
                cnt ++
; t /= 10; } else t /= 10; } } cout << cnt; return 0; }
  • If you have any questions,please feel free to communicate with me.