使用 k 位数字计算幸运数数目的 C++ 代码
假设我们有一个包含 n 个元素的数组 A,以及另一个数字 x。众所周知,幸运数字是仅包含幸运数字 4 和 7 的十进制数字。从给定的 n 个正整数中,我们必须计算其中有多少个数字不超过 k 个幸运数字?
因此,如果输入为 A = [44, 74, 474, 154]; k = 2,则输出为 3,因为有三个幸运数字 44、74 和 474,但 474 有三个幸运数字,这比 k 多。此外,154 有一个幸运数字,这是可以接受的。
步骤
要解决此问题,我们将遵循以下步骤 -
n := size of A f := 0 for initialize i := 0, when i < n, update (increase i by 1), do: c := 0 while A[i] is not equal to 0, do: if A[i] mod 10 is same as 4 or A[i] mod 10 is same as 7, then: (increase c by 1) A[i] := A[i] / 10 if c <= k, then: (increase f by 1) return f
示例
让我们看看以下实现以获得更好的理解 -
#include<bits/stdc++.h>
using namespace std;
int solve(vector<int> A, int k){
int n = A.size();
int f = 0;
for (int i = 0; i < n; ++i){
int c = 0;
while (A[i] != 0){
if (A[i] % 10 == 4 || A[i] % 10 == 7)
c++;
A[i] /= 10;
}
if (c <= k)
f++;
}
return f;
}
int main(){
vector<int> A = {44, 74, 474, 154};
int k = 2;
cout << solve(A, k) << endl;
}输入
{44, 74, 474, 154}, 2输出
3
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP