Binary Prefix Divisible By 5

Given an array A of 0s and 1s, 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<boolprefixesDivBy5(vector<int&A)
{

    vector<boolres;
    int sum = 0;
    for (auto a : A)
    {
        sum = (sum * 2 + a) % 5;
        res.push_back(sum == 0);
    }
    return res;
}
int main()
{
    vector<intA = {011};

    vector<boolans = prefixesDivBy5(A);

    cout << "[";
    for (int i = 0i < ans.size() - 1i++)
    {
        if (ans[i] == 0)
            cout << "false,";
        else
            cout << "true,";
    }
    if (ans[ans.size() - 1] == 0)
        cout << "false";
    else
        cout << "true";
    cout << "]";

    return 0;
}


No comments:

Post a Comment