-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1018. Binary Prefix Divisible By 5.c
80 lines (74 loc) · 1.77 KB
/
1018. Binary Prefix Divisible By 5.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/** C
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
bool* prefixesDivBy5(int* A, int ASize, int* returnSize) {
bool *preturn = malloc(sizeof(bool)*ASize);
int i=0 , counter = 0;
*returnSize=ASize;
for (i=0;i<ASize;i++) {
counter = (counter*2 + *(A+i))%5;
//printf("%d ",counter);
if (counter==0)
*(preturn+i)=1;
else
*(preturn+i)=0;
}
/* printf("\n");
for (i=0;i<ASize;i++) {
printf("%d ",*(preturn+i));
}*/
return preturn;
}
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
bool* prefixesDivBy5(int* A, int ASize, int* returnSize){
*returnSize = ASize;
bool* res = malloc(ASize*sizeof(bool));
int tmp = 0;
for(int i=0; i<ASize; i++)
res[i] = (tmp = (A[i] + (tmp<<1)) % 5) ? false : true;
return res;
}
bool* prefixesDivBy5(int* A, int ASize, int* returnSize)
{
int value = 0;
bool* result = (bool*)malloc(sizeof(bool) * ASize);
for (int i = 0; i <= ASize - 1; i++)
{
value = (value * 2 + A[i]) % 5;
result[i] = value ? false : true;
}
*returnSize = ASize;
return result;
}
/** Javascript */
/**
* @param {number[]} A
* @return {boolean[]}
*/
var prefixesDivBy5 = function (A) {
if (A == null) return A;
const r = new Array(A.length)
let total = 0
for (let i = 0; i < A.length; i++) {
total = ((total << 1) + A[i]) % 5
r[i] = total === 0
}
return r
};
/**
* @param {number[]} A
* @return {boolean[]}
*/
var prefixesDivBy5 = function(A) {
let res = [];
A.reduce((acc, cur) => {
acc = (acc*2 + cur)%5
res.push(acc === 0);
return acc;
}, 0);
return res;
};