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 1:

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.
Example 2:

Input: [1,1,1]
Output: [false,false,false]
Example 3:

Input: [0,1,1,1,1,1]
Output: [true,false,false,false,true,false]
Example 4:

Input: [1,1,1,0,1]
Output: [false,false,false,false,false]
 

Note:

1 <= A.length <= 30000
A[i] is 0 or 1

这题就是求一个二进制表示的数字是否能被5整除。数字是以一个vector来给定的,我们要不断的增加长度来判断是否满足条件。

这题直接暴力解了,不断的算出十进制数字,然后判断能否整除。需要注意的是,在读取下一个数字的时候,我们需要给之前的数字进位,由于是二进制,所以需要乘以2;同时为了防止移除,我们需要对保存的和对5取余,只看余数是否能满足条件。

class BinayrPrefixDivisbleBy5 : public Solution {
    public:
    void Exec() {

    }
    vector<bool> prefixesDivBy5(vector<int>& A) {
        int sum = 0;
        vector<bool> res;
        res.reserve(A.size());

        for (int i = 0; i < A.size(); i++) {
            sum = sum * 2 + (A[i] == 0 ? 0 : 1);
            res.push_back(sum % 5 == 0);
            sum %= 5;
        }
        return res;
    }
};
共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day