You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
Given an array
A
of0
s and1
s, considerN_i
: the i-th subarray fromA[0]
toA[i]
interpreted as a binary number (from most-significant-bit to least-significant-bit.)Return a list of booleans
answer
, whereanswer[i]
istrue
if and only ifN_i
is divisible by 5.Example 1:
Example 2:
Example 3:
Example 4:
Note:
1 <= A.length <= 30000
A[i]
is0
or1
这道题给了一个只由0和1组成的数组,问从0开始每个子数组表示的二进制数是否可以整除5,二进制数是从高位到低位的。既然是一道 Easy 的题目,也就不用太多的技巧,直接按顺序遍历即可。首先对于第一个数字,可以快速知道其是否可以整除5,当子数组新加一位,实际上相当于之前的数字左移了一位,也就相当于乘以了2,所以新的子数组表示的数字就是之前的数字乘以2再加上新加进来的数字,然后就可以判断是否可以整除5了。但是需要注意的一点是,由于A数组可能会很长,所以最终累加出来的数字可能会很大,超过整型最大值,甚至也超过长整型的最大值,为了避免这种情况,对每次累加出来的新数字都对5取余,这样就不会溢出了,参见代码如下:
Github 同步地址:
#1018
参考资料:
https://leetcode.com/problems/binary-prefix-divisible-by-5/
https://leetcode.com/problems/binary-prefix-divisible-by-5/discuss/265601/Detailed-Explanation-using-Modular-Arithmetic-O(n)
https://leetcode.com/problems/binary-prefix-divisible-by-5/discuss/265554/JavaPython-3-71-liners-left-shift-bitwise-or-and-mod.
LeetCode All in One 题目讲解汇总(持续更新中...)
The text was updated successfully, but these errors were encountered: