1018. Binary Prefix Divisible By 5 #2458
-
|
Topics: You are given a binary array We define
Return an array of booleans Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We cannot directly convert the binary number to an integer due to potential overflow issues. Instead, we use modular arithmetic to efficiently compute the remainder when the number is divided by 5 at each step. Approach
Let's implement this solution in PHP: 1018. Binary Prefix Divisible By 5 <?php
/**
* @param Integer[] $nums
* @return Boolean[]
*/
function prefixesDivBy5($nums) {
$current = 0;
$result = [];
foreach ($nums as $bit) {
$current = ($current * 2 + $bit) % 5;
$result[] = $current === 0;
}
return $result;
}
// Test cases
echo prefixesDivBy5([0,1,1]) . "\n"; // Output: [true,false,false]
echo prefixesDivBy5([1,1,1]) . "\n"; // Output: [false,false,false]
?>Explanation:
|
Beta Was this translation helpful? Give feedback.
We cannot directly convert the binary number to an integer due to potential overflow issues. Instead, we use modular arithmetic to efficiently compute the remainder when the number is divided by 5 at each step.
Approach
ibits, the number formed by the firsti+1bits can be expressed as(current_value * 2 + next_bit). By taking the modulo 5 of this value at each step, we keep the current value manageable and within a small range (0 to 4).current = (current * 2 + bit) % 5. This ensures that we only track the remainde…