ในปัญหานี้ เราได้รับอาร์เรย์ งานของเราคือตรวจสอบว่าตัวเลขที่สร้างจากการใช้ทุกหลักขององค์ประกอบของอาร์เรย์หาร 3 ลงตัวหรือไม่ หากเป็นไปได้พิมพ์ "Yes" มิฉะนั้นพิมพ์ "No"
มาดูตัวอย่างเพื่อเข้าใจปัญหา
Input - arr = {3, 5, 91}
Output - YES
Explanation - ตัวเลข 5193 หาร 3 ลงตัว ดังนั้นคำตอบของเราคือ YES
เพื่อแก้ปัญหานี้ เราจะตรวจสอบการหาร 3 ลงตัว
Divisibility by 3 - ตัวเลขหาร 3 ลงตัว หากผลรวมของหลักของมันหาร 3 ลงตัว
ตอนนี้ เราจะต้องหาผลรวมของทุกองค์ประกอบของอาร์เรย์ หากผลรวมนี้หาร 3 ลงตัว แล้วเป็นไปได้ที่จะพิมพ์ YES มิฉะนั้น No
ตัวอย่าง
โปรแกรมแสดงการนำโซลูชันของเราไปใช้งาน:
#include <iostream>
using namespace std;
bool is3DivisibleArray(int arr[]) {
int n = sizeof(arr) / sizeof(arr[0]);
int rem = 0;
for (int i = 0; i < n; i++)
rem = (rem + arr[i]) % 3;
return (rem == 0);
}
int main() {
int arr[] = { 23, 64, 87, 12, 9 };
cout << "Creating a number from digits of array which is divisible by 3 ";
is3DivisibleArray(arr) ? cout << "is Possible" : cout << "is not Possible";
return 0;
}
ผลลัพธ์
Creating a number from digits of array which is divisible by 3 is Possible