Binary Prefix Divisible By 5 LeetCode solution in C++

1
class Solution {
2
public:
3
/*
4
1. We notice that 1 = 1; 10 = 1*2 + 0 = 2; 101 = 2*2 + 1 = 5; .Therefore, the
5
current_decimal form of number = previous sum * 2 + nums[i];
6
2. It means: current_number = current_number * 2 + nums[i] (i = current index)
7
3. If we did that, the current_number will exceed integer limit => Therefore,
8
we modulo the current_number by 5. We check if the remainder equals to 0 or
9
not. By doing that, we can keep our current_number from 0 to 4, which will not
10
exceed integer range.
11
*/
12
vector<bool> prefixesDivBy5(vector<int> &nums) {
13
vector<bool> answer;
14
int current_number = 0;
15
for (int i = 0; i < nums.size(); i++) {
16
current_binary = (current_number * 2 + nums[i]) % 5;
17
if (current_number == 0)
18
answer.push_back(true);
19
else
20
answer.push_back(false);
21
}
22
return answer;
23
}
24
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0