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

จำนวนกลุ่มแม่เหล็กที่เกิดจาก N แม่เหล็กใน C++


เลข 1 = ขั้วบวก, 0 = ขั้วลบ แม่เหล็กเป็น "10" หรือ "01" กลุ่มเกิดเมื่อแม่เหล็กดึงดูดกัน (ขั้วต่างกันติดกัน) นับจำนวนกลุ่ม

ตัวอย่าง:

Input: magnets = ["10", "01", "01", "01", "10", "01"]
Output: 4

อัลกอริทึม

  • count = 1
  • วน i = 1 ถึง n-1:
    • ถ้า magnets[i] != magnets[i-1] count++
  • คืนค่า count

การเขียนโปรแกรม C++

#include <bits/stdc++.h> using namespace std; int getMangetGroupsCount(string magnets[], int n) {    int count = 1;    for (int i = 1; i < n; i++) if (magnets[i] != magnets[i - 1]) count++;    return count; } int main() {    string magnets[] = { "10", "01", "01", "01", "10", "01" };    int n = 6;    cout << getMangetGroupsCount(magnets, n) << endl;    return 0; }

ผลลัพธ์

4