假设我们有一个包含 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