1018. Binary Prefix Divisible By 5

You are given a binary array nums (0-indexed).

We define x i x_i xi as the number whose binary representation is the subarray nums[0…i] (from most-significant-bit to least-significant-bit).

  • For example, if nums = [1,0,1], then x 0 = 1 , x 1 = 2 , a n d x 2 = 5 x_0 = 1, x_1 = 2, and x_2 = 5 x0=1,x1=2,andx2=5.

Return an array of booleans answer where answer[i] is true if x i x_i xi is divisible by 5.
 

Example 1:

Input: nums = [0,1,1]
Output: [true,false,false]
Explantion: 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: nums = [1,1,1]
Output: [false,false,false]

Constraints:
  • 1 < = n u m s . l e n g t h < = 10 5 1 <= nums.length <= 10^5 1<=nums.length<=105
  • nums[i] is either 0 or 1.

From: LeetCode
Link: 1018. Binary Prefix Divisible By 5


Solution:

Ideas:
  • Let the current prefix value be x.

  • When a new bit b is appended, the new value becomes x * 2 + b.

  • We only care whether it is divisible by 5, so keep x % 5 instead of the full number.

  • Update with rem = (rem * 2 + nums[i]) % 5.

  • If rem == 0, that prefix is divisible by 5.

Code:
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
bool* prefixesDivBy5(int* nums, int numsSize, int* returnSize) {
    *returnSize = numsSize;
    bool* ans = (bool*)malloc(sizeof(bool) * numsSize);
    
    int rem = 0;  // current prefix value modulo 5
    
    for (int i = 0; i < numsSize; i++) {
        rem = (rem * 2 + nums[i]) % 5;
        ans[i] = (rem == 0);
    }
    
    return ans;
}
Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐