comments | difficulty | edit_url | rating | source | tags | |||
---|---|---|---|---|---|---|---|---|
true |
中等 |
1541 |
第 334 场周赛 Q2 |
|
给你一个下标从 0 开始的字符串 word
,长度为 n
,由从 0
到 9
的数字组成。另给你一个正整数 m
。
word
的 可整除数组 div
是一个长度为 n
的整数数组,并满足:
- 如果
word[0,...,i]
所表示的 数值 能被m
整除,div[i] = 1
- 否则,
div[i] = 0
返回 word
的可整除数组。
示例 1:
输入:word = "998244353", m = 3 输出:[1,1,0,0,0,1,1,0,0] 解释:仅有 4 个前缀可以被 3 整除:"9"、"99"、"998244" 和 "9982443" 。
示例 2:
输入:word = "1010", m = 10 输出:[0,1,0,1] 解释:仅有 2 个前缀可以被 10 整除:"10" 和 "1010" 。
提示:
1 <= n <= 105
word.length == n
word
由数字0
到9
组成1 <= m <= 109
我们遍历字符串 word
,用变量
时间复杂度 word
的长度。空间复杂度
class Solution:
def divisibilityArray(self, word: str, m: int) -> List[int]:
ans = []
x = 0
for c in word:
x = (x * 10 + int(c)) % m
ans.append(1 if x == 0 else 0)
return ans
class Solution {
public int[] divisibilityArray(String word, int m) {
int n = word.length();
int[] ans = new int[n];
long x = 0;
for (int i = 0; i < n; ++i) {
x = (x * 10 + word.charAt(i) - '0') % m;
if (x == 0) {
ans[i] = 1;
}
}
return ans;
}
}
class Solution {
public:
vector<int> divisibilityArray(string word, int m) {
vector<int> ans;
long long x = 0;
for (char& c : word) {
x = (x * 10 + c - '0') % m;
ans.push_back(x == 0 ? 1 : 0);
}
return ans;
}
};
func divisibilityArray(word string, m int) (ans []int) {
x := 0
for _, c := range word {
x = (x*10 + int(c-'0')) % m
if x == 0 {
ans = append(ans, 1)
} else {
ans = append(ans, 0)
}
}
return ans
}
function divisibilityArray(word: string, m: number): number[] {
const ans: number[] = [];
let x = 0;
for (const c of word) {
x = (x * 10 + Number(c)) % m;
ans.push(x === 0 ? 1 : 0);
}
return ans;
}
impl Solution {
pub fn divisibility_array(word: String, m: i32) -> Vec<i32> {
let m = m as i64;
let mut x = 0i64;
word.as_bytes()
.iter()
.map(|&c| {
x = (x * 10 + i64::from(c - b'0')) % m;
if x == 0 {
1
} else {
0
}
})
.collect()
}
}
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* divisibilityArray(char* word, int m, int* returnSize) {
int n = strlen(word);
int* ans = malloc(sizeof(int) * n);
long long x = 0;
for (int i = 0; i < n; i++) {
x = (x * 10 + word[i] - '0') % m;
ans[i] = x == 0 ? 1 : 0;
}
*returnSize = n;
return ans;
}