2575.找出字符串的可整除数组
链接:2575.找出字符串的可整除数组
难度:Medium
标签:数组、数学、字符串
简介:返回 word 的可整除数组。
题解 1 - cpp
- 编辑时间:2023-02-26
- 执行用时:32ms
- 内存消耗:25.8MB
- 编程语言:cpp
- 解法介绍:遍历。
class Solution {
public:
    vector<int> divisibilityArray(string word, int m) {
        vector<int> ans;
        long long cur = 0;
        for (auto &c : word) {
            cur = (cur * 10 + c - '0') % m;
            int num = cur == 0 ? 1 : 0;
            ans.push_back(num);
        }
        return ans;
    }
};
题解 2 - rust
- 编辑时间:2023-02-26
- 执行用时:36ms
- 内存消耗:3MB
- 编程语言:rust
- 解法介绍:同上。
impl Solution {
        pub fn divisibility_array(word: String, m: i32) -> Vec<i32> {
            let word = word.chars().collect::<Vec<char>>();
            let m = m as i64;
            let mut ans = vec![];
            let mut cur = 0i64;
            for c in word {
                cur = (cur * 10 + c as i64 - '0' as i64) % m;
                ans.push(if cur == 0 { 1 } else { 0 })
            }
            ans
        }
    }
题解 3 - python
- 编辑时间:2023-02-26
- 执行用时:164ms
- 内存消耗:18.1MB
- 编程语言:python
- 解法介绍:同上。
class Solution:
    def divisibilityArray(self, word: str, m: int) -> List[int]:
        ans = []
        cur = 0
        for c in word:
            cur = (cur * 10 + ord(c) - ord('0')) % m
            ans.append(1 if cur == 0 else 0)
        return ans
题解 4 - python
- 编辑时间:2024-03-07
- 执行用时:159ms
- 内存消耗:19.35MB
- 编程语言:python
- 解法介绍:遍历时累加取模。
class Solution:
    def divisibilityArray(self, word: str, m: int) -> List[int]:
        ans = []
        cur = 1-1
        for c in word:
            cur = (cur * (11 - 1) + int(c)) % m
            ans.append(int(cur == 1-1))
        return ans