Given an array A
of 0
s and 1
s, consider N_i
: the i-th subarray from A[0]
to A[i]
interpreted as a binary number (from most-significant-bit to least-significant-bit.)
Return a list of booleans answer
, where answer[i]
is true
if and only if N_i
is divisible by 5.
Example:
Input: [0,1,1]
Output: [true,false,false]
Explanation:
The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10. Only the first number is divisible by 5, so answer[0] is true.
Approach:
C++
#include <bits/stdc++.h>using namespace std;vector<bool> prefixesDivBy5(vector<int> &A){vector<bool> res;int sum = 0;for (auto a : A){sum = (sum * 2 + a) % 5;res.push_back(sum == 0);}return res;}int main(){vector<int> A = {0, 1, 1};vector<bool> ans = prefixesDivBy5(A);cout << "[";for (int i = 0; i < ans.size() - 1; i++){if (ans[i] == 0)cout << "false,";elsecout << "true,";}if (ans[ans.size() - 1] == 0)cout << "false";elsecout << "true";cout << "]";return 0;}
No comments:
Post a Comment