天天看點

LeetCode-Binary Prefix Divisible By 5

Description:

Given an array A of 0s and 1s, consider N_i: the i-th subarray from A[0] to A[i] interpreted as a binary number (from most-significant-bit to least-significant-bit.)

Return a list of booleans answer, where answer[i] is true if and only if N_i is divisible by 5.

Example 1:

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

Note:

  • 1 <= A.length <= 30000
  • A[i] is 0 or 1

題意:給定一個數組A,僅包含0或1;定義N_i為以A[0],A[1],…A[i]表示的數,計算N_i是否能被5整除;

解法:我們知道能被5整除的數必定滿足最後一位的數字為0或者5;是以我們隻需要判斷N_i的最後一位是否滿足即可,即計算

是否滿足條件即可;

Java
class Solution {
    public List<Boolean> prefixesDivBy5(int[] A) {
        List<Boolean> res = new ArrayList<>();
        int num = 0;
        for (int a: A) {
            num = (num << 1) % 10 + a;
            res.add(num == 0 || num == 5 ? true : false);
        }
        
        return res;
    }
}