原文链接: https://leetcode-cn.com/problems/binary-prefix-divisible-by-5
英文原文
You are given a binary array nums (0-indexed).
We define 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], thenx0 = 1,x1 = 2, andx2 = 5.
Return an array of booleans answer where answer[i] is true if xi is divisible by 5.
Example 1:
Input: nums = [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: nums = [1,1,1] Output: [false,false,false]
Example 3:
Input: nums = [0,1,1,1,1,1] Output: [true,false,false,false,true,false]
Example 4:
Input: nums = [1,1,1,0,1] Output: [false,false,false,false,false]
Constraints:
1 <= nums.length <= 105nums[i]is0or1.
中文题目
给定由若干 0 和 1 组成的数组 A。我们定义 N_i:从 A[0] 到 A[i] 的第 i 个子数组被解释为一个二进制数(从最高有效位到最低有效位)。
返回布尔值列表 answer,只有当 N_i 可以被 5 整除时,答案 answer[i] 为 true,否则为 false。
示例 1:
输入:[0,1,1] 输出:[true,false,false] 解释: 输入数字为 0, 01, 011;也就是十进制中的 0, 1, 3 。只有第一个数可以被 5 整除,因此 answer[0] 为真。
示例 2:
输入:[1,1,1] 输出:[false,false,false]
示例 3:
输入:[0,1,1,1,1,1] 输出:[true,false,false,false,true,false]
示例 4:
输入:[1,1,1,0,1] 输出:[false,false,false,false,false]
提示:
1 <= A.length <= 30000A[i]为0或1
通过代码
高赞题解
有限状态机
状态对应(mod 5),箭头表示状态转移,转移函数是(当前状态*2+二进制数末位)%5。
代码
impl Solution {
pub fn prefixes_div_by5(a: Vec<i32>) -> Vec<bool> {
let mut state: i32 = 0;
let mut result = vec![];
let stateSet = [[0, 1], [2, 3], [4, 0], [1, 2], [3, 4]];
for i in a {
state = stateSet[state as usize][i as usize];
result.push(state == 0);
}
result
}
}
统计信息
| 通过次数 | 提交次数 | AC比率 |
|---|---|---|
| 44583 | 86434 | 51.6% |
提交历史
| 提交时间 | 提交结果 | 执行时间 | 内存消耗 | 语言 |
|---|