Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

นับจำนวนที่มีหลักหน่วยเป็น k ในช่วงที่กำหนด ใน C++

ได้รับช่วง [first, last] และตัวเลข k ต้องการนับจำนวนในช่วงนี้ที่มีหลักหน่วยเท่ากับ k

ตัวอย่าง

อินพุต: first = 8, last = 40, k = 8

เอาต์พุต: 4

คำอธิบาย: 8, 18, 28, 38

อินพุต: first = 100, last = 200, k = 9

เอาต์พุต: 10

คำอธิบาย: 109, 119, 129, 139, 149, 159, 169, 179, 189, 199

แนวทาง

  • วนลูป i จาก first ถึง last
  • หาหลักหน่วยด้วย i % 10
  • ถ้าเท่ากับ k เพิ่มตัวนับ

ตัวอย่างโค้ด C++

#include <bits/stdc++.h>
using namespace std;

int getCount(int fst, int lst, int k) {
    int count = 0;
    for (int i = fst; i <= lst; i++) {
        int ldigit = i % 10;
        if (ldigit == k) {
            ++count;
        }
    }
    return count;
}

int main() {
    int first = 5, last = 30;
    int K = 5;
    cout << "Numbers with unit digit K in range: " << getCount(first, last, K);
    return 0;
}

ผลลัพธ์

Numbers with unit digit K in range: 3