在 C++ 中查詢給定數字在由 4 和 7 組成的數字中的位置
在這個問題中,我們給定一個數字 N。我們的任務是找到給定數字在僅由 4 和 7 組成的數字中的位置。該序列僅由 4 和 7 組成,例如 4, 7, 44, 47, 74, 77, 444…
讓我們來看一個例子來理解這個問題:
輸入
N = 5
輸出
74
解釋
Series upto 5 terms is 4, 7, 44, 47, 74…
解決方案方法
這個問題的一個簡單的解決方案是基於查詢序列中的模式。
這裡,每個偶數位置的結尾都是 7。
每個奇數位置的結尾都是 4。
因此,我們可以逐位查詢序列,並根據當前數字查詢位置。
如果當前數字是 4,則位置將更新為 position = (position*2) + 1。
如果當前數字是 7,則位置將更新為 position = (position*2) + 2。
程式說明了我們解決方案的工作原理:
示例
#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;
}輸出
The position of the number in the series is 53
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP