กำหนดอาร์เรย์ของหลุม [10] ที่มีจำนวนหลุมในตัวเลข 0 ถึง 9 เป้าหมายคือการหาจำนวนหลุมในจำนวนเต็มที่กำหนดให้เป็นอินพุต ให้ − หลุม[] ={ 2, 1, 1, 0, 0, 1, 1, 1, 0 }
ตัวอย่าง
อินพุต
number = 239143
ผลลัพธ์
Count the number of holes in an integer are: 3
คำอธิบาย
We will count holes given in holes[] 239143 ( 1+0+0+2+0+0 )
อินพุต
number = 12345
ผลลัพธ์
Count the number of holes in an integer are: 3
คำอธิบาย
We will count holes given in holes[] 12345 ( 1+1+0+0+1)
แนวทางที่ใช้ในโปรแกรมด้านล่างมีดังนี้ −
เพียงใช้ตัวเลขซ้ายสุดแต่ละหลักโดยใช้ num%10 และเพิ่มจำนวนรูจากรู[num%10]เพื่อนับ แล้วลดจำนวนลง 10
-
ใช้จำนวนเต็มเป็นอินพุต
-
เริ่มต้นอาร์เรย์[] ของรู
-
ฟังก์ชัน holes_integer(int number, int holes[]) ส่งคืนค่าจำนวนหลุมในจำนวนเต็ม
-
นับเริ่มต้นเป็น 0
-
ข้ามจนถึงหมายเลข> 0
-
ใช้หลักซ้ายสุดเป็น temp =หมายเลข % 10 เพิ่ม holes[temp] เพื่อนับ
-
ลดจำนวนลง 10
-
ผลตอบแทนนับเป็นผลลัพธ์ในตอนท้าย
ตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
int holes_integer(int number, int holes[]){
int count = 0;
while (number > 0){
int temp = number % 10;
count = count + holes[temp];
number = number/10;
}
return count;
}
int main(){
int number = 239143;
int holes[] = { 2, 1, 1, 0, 0, 1, 1, 1, 0};
cout<<"Count the number of holes in an integer are: "<<holes_integer(number, holes);
return 0;
} ผลลัพธ์
หากเราเรียกใช้โค้ดข้างต้น มันจะสร้างผลลัพธ์ต่อไปนี้ -
Count the number of holes in an integer are: 2