Trong bài toán này, cho số N. Nhiệm vụ là tìm vị trí của số trong dãy chỉ chứa chữ số 4 và 7. Dãy: 4, 7, 44, 47, 74, 77, 444...
Ví dụ minh họa:
Đầu vào
N = 5
Đầu ra
74
Giải thích
Dãy đến hạng 5: 4, 7, 44, 47, 74...
Phương pháp giải
Dựa trên quy luật: vị trí chẵn kết thúc bằng 7, vị trí lẻ kết thúc bằng 4. Xử lý từng chữ số: nếu là 4, position = position*2 + 1; nếu là 7, position = position*2 + 2.
Chương trình minh họa:
Ví dụ
#include <iostream>
using namespace std;
int findNumPosition(string num){
int i = 0, position = 0;
while (num[i] != '\0') {
position *= 2;
if(num[i] == '4') position += 1;
else position += 2;
i++;
}
return position;
}
int main() {
string num = "74774";
cout<<"The position of the number in the series is "<<findNumPosition(num);
return 0;
}Kết quả
The position of the number in the series is 53