Cho chuỗi số num. Đếm tổng số thay đổi LED khi hiển thị lần lượt các chữ số trên màn hình 7 đoạn (giả sử ban đầu tất cả LED tắt).
Màn hình 7 đoạn (Seven Segment Display)
Mỗi chữ số dùng 7 LED (a-g). Số LED sáng cho từng chữ số: 0:6, 1:2, 2:5, 3:5, 4:4, 5:5, 6:6, 7:3, 8:7, 9:5


Ví dụ
"123" → LED(1)=2, LED(2)=5, LED(3)=5. Thay đổi: |2-0| + |5-2| + |5-5| = 2+3+0 = 5
"576" → 5+3+6, thay đổi: 5 + |3-5| + |6-3| = 5+2+3 = 10
Phương pháp
Khởi tạo mảng Led[10] = {6,2,5,5,4,5,6,3,7,5}. res = Led[first_digit]. Duyệt từ ký tự thứ 2: res += abs(Led[current] - Led[prev]).
Ví dụ minh họa (C++)
#include <iostream>
using namespace std;
int countled(string str) {
int Led[] = { 6, 2, 5, 5, 4, 5, 6, 3, 7, 5 };
int len = str.length();
int res = Led[str[0] - '0'];
for (int i = 1; i < len; i++) {
res = res + abs(Led[str[i] - '0'] - Led[str[i - 1] - '0']);
}
return res;
}
int main() {
string str = "123";
cout << "count is " << countled(str);
return 0;
}
Đầu ra
count is 5