Subject: 1018. Binary prefix divisible by 5
Given an array A consisting of a number of 0 and 1. We define N_i: the i-th sub-array from A[0] to A[i] is interpreted as a binary number (from the most significant bit to the least significant bit).
Returns a list of boolean values answer, only when N_i is divisible by 5, the answer[i] is true, otherwise it is false.
Source: LeetCode
Link: https://leetcode-cn.com/problems/binary-prefix-divisible-by-5 The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Example
Example 1:
Input: [0,1,1]
Output: [true,false,false]
Explanation: The
input numbers are 0, 01, 011; that is, 0, 1, 3 in decimal. 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]
prompt:
1 <= A.length <= 30000
A[i] 为 0 或 1
answer:
answer
bool* prefixesDivBy5(int* A, int ASize, int* returnSize){
bool * Array = (int *)malloc(sizeof(bool) * ASize);
int i;
int b=0;
for(i=0;i<ASize;i++){
b=b*2+A[i];
b=b%5;
//b是0的时候为真,其他为假
if(!b)
Array[i]=true;
else
Array[i]=false;
}
*returnSize=ASize;
return Array;
}
Note:
Note:
1. Pay attention to the order, see Example 1
2. Prevent the number from being too large, and obtain the remainder as a new number b after dividing by 5, and then add A[i] 3. When b
is 0, it is true, and the others are false
4. .I didn't understand why *returnSize=ASize; this was added by looking at the solution.